ajax一定要用回调来实现吗

38 阅读1分钟

回调函数版本ajax

image.png

不一定promise版本就可以不用回调

function ajax(url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();  
        // 设置请求的类型、URL等信息
        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作用,就是为了代替回调,回调容易写成嵌套