Promise,异步编程的一种解决方案,简单可以理解为,一个容器内保存着未来结束的事件(通常为异步操作)。
Promise优点:
(1)、对象状态不受外界影响
(2)、一旦状态改变,就不会再变,任何时候都可以得到这个结果。
基本用法:
const promise= new Promise(fucntion(resolve,reject){
if(/*异步成功*/){
resolve(value)
}else{
reject(err)
}
})
promise.then(function(res){
//成功
console.log(res)
},function(err){
//失败
console.log(err)
})
Promise封装ajax实例
const ajaxFn = new Promise((resolve,reject) => {
//1、创建对象
const xhr = new XMLHtppRequest();
//2、初始化
xhr.open('get','http://www.baidu.com');
//3、发送
xhr.send();
//4、绑定事件,处理结果
xhr.onreadystatechange = function(){
//判断状态
if(xhr.readyState == 4){
//判断状态码
if(xhr.status == 200){
resolve(xhr.response)
}else{
rerject(xhr.status)
}
}
}
})
//指定回调
ajaxFn.then(function(res){
console.log(res)
},function(err){
console.log(err)
})