Promise 封装 Ajax
// Promise 封装 ajax
function ajax(method, url, data){
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
var method = method || "GET";
var data = data || null;
xhr.open(method, url, true);
xhr.onreadystatechange = function() {
if(xhr.status === 200 && xhr.readyState === 4){
resolve(xhr.responseText);
} else {
reject(xhr.responseText);
}
}
xhr.send(data);
})
}
// 使用
ajax("GET", "/some/url.json", null)
.then(result => {
console.log(result);
})
Promise链式(避免回调函数的嵌套)
- Promise 对象的 then 方法会返回一个全新的 Promise 对象
- 后面的 then 方法就是在为上一个 then 返回的 Promise 注册对象
- 前面 then 方法的返回值会作为后面 then 方法回调的参数
- 如果回调中返回的是 Promise ,那么后面 then 方法的回调会等待它的结束
Promise 捕获异常
//捕获异常
ajax('/api/foo.json')
.then(function onFulfilled (value) {
console.log('onFulfilled', value)
return ajax(&