Promise将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数
//1.promise 封装Ajax
const p = new Promise((resolve, reject) => {
//创建对象
const xhr = new XMLHttpRequest();
//初始化
xhr.open('GET', 'https://api.apiopen.top/getJoke');
//发送
xhr.send();
//绑定事件,处理响应结果
xhr.onreadystatechange = function() {
//判断
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
} else {
reject(xhr.status);
}
}
}
})
p.then(function(value){
console.log(value);
},function(reason){
console.error(reason);
})
-
Promise 对象的 then 方法会返回一个全新的 Promise 对象