回调函数版本ajax

不一定promise版本就可以不用回调
function ajax(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(new Error(`Request failed with status ${xhr.status}`));
}
};
xhr.onerror = function() {
reject(new Error("Network error occurred"));
};
xhr.send();
});
}
const apiUrl = "https://api.example.com/data";
ajax(apiUrl).then(result => {
console.log(result);
}).catch(err => {
console.error(err);
});
promise作用,就是为了代替回调,回调容易写成嵌套