Promise:相当于一个容器,保存者未来才会结束的事件及将要返回的结果;
Promise特点:
1.)对象的状态不受外界影响,处理异步操作共包含三个状态(Pending/进行中,Resolved/成功,Reject/失败);
2.)一旦状态改变,就不会在变,任何时候都可以得到这个结果
简单案例:
let pro = new Promise(function(resolved,rejected){
let res ={
code:200,
data:{
name:'wangwu'
},
err:'失败'
}
setTimeout(() => {
if(res.code === 201){
resolved(res.data);
}else{
rejected(res.err);
}
}, 1000);
})
pro.then((val)=>{
console.log(val);
},(err)=>{
console.log(err);
});
封装案例:
function timeOut(ms) {
return new Promise((resolved, rejected) => {
setTimeout(() => {
resolved('hello promise');
}, ms);
});
}
timeOut(2000).then((val) => {
console.log(val);
}).catch(err => {
console.log(err);
});
console.log("ss");
All方法:(异步并行),加载素材时可以使用
let promise1 = new Promise((resolved, rejected) => { });
let promise2 = new Promise((resolved, rejected) => { });
let promise3 = new Promise((resolved, rejected) => { });
let promise4 = Promise.all([promise1, promise2, promise3]); //异步并发执行,并返回一个Promise
//所有并发执行成功后继续操作
promise4.then((val) => {
}).catch((err) => {
});
race方法:将执行动作Promise和超时动作Promise放到数组中,超时后将执行超时动作
function requestImage(imgSrc) {
return new Promise((resolved, rejected) => {
const img = new Image();
img.src = imgSrc;
img.onload = function () {
resolved(img);
}
});
}
function timeOut() {
return new Promise((resolved, rejected) => {
setTimeout(function () {
rejected("图片请求失败");
}, 1000);
});
}
Promise.race([requestImage('https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1604562391&di=b9f3808e12abf31f184609414aa6d94c&src=http://a0.att.hudong.com/56/12/01300000164151121576126282411.jpg'), timeOut()]).then((data) => {
document.body.appendChild(data);
}).catch((err) => {
console.log(err);
});