1.将传统的ajax调用改写为promise的方式
function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
get('story.json').then(function(response) {
console.log("Success!", response);
}, function(error) {
console.error("Failed!", error);
})
2.当从 then() 回调中返回某些内容时,如果返回一个值,则会以该值调用下一个 then()。但是,如果返回类promise 的内容,下一个then() 则会等待,并仅在 promise 产生结果(成功/失败)时调用。
本文介绍了如何通过使用Promise模式来改进传统的AJAX调用,使异步操作更加简洁且易于管理。文章首先展示了如何将一个普通的AJAX请求转换为Promise形式,接着解释了在Promise链中如何处理成功和失败的情况,最后讨论了从then()回调中返回不同类型的值对后续Promise调用的影响。
3608

被折叠的 条评论
为什么被折叠?



