Promise的基本用法,基于Promise处理ajax请求
warning:
这篇文章距离上次修改已过191天,其中的内容可能已经有所变动。
// 假设我们有一个函数用于发送AJAX请求
function sendAjaxRequest(url, method, data) {
// 返回一个Promise对象
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(new Error("Error: " + xhr.status));
}
}
};
xhr.send(JSON.stringify(data));
});
}
// 使用Promise来处理AJAX请求
sendAjaxRequest("https://api.example.com/data", "GET", null)
.then(function(response) {
console.log("Success:", response);
// 进一步处理响应数据
})
.catch(function(error) {
console.error("Error:", error);
});
这段代码展示了如何使用Promise处理一个简单的AJAX请求。sendAjaxRequest
函数返回一个Promise对象,它将在请求成功完成时调用resolve
,或在请求失败时调用reject
。然后我们可以使用.then()
来处理成功的情况,使用.catch()
来处理错误。这是现代JavaScript中异步编程的一个常见模式。
评论已关闭