Promise:解決非同步回撥問題
let a=10;
let promise = new Promise(function(resolve,reject){
//resolve,成功時呼叫
//reject,失敗時呼叫
if (a==10) {
resolve('成功')
}else{
reject('失敗')
}
});
// promise.then(success,fail);
promise.then(res=>{
console.log(res);//成功
})
複製程式碼
Promise.all([p1,p2,……])
let p2= Promise.resolve('bbb');
let p3=Promise.resolve('ccc');
let p4=Promise.resolve('ddd');
Promise.all([p2,p3,p4]).then(res=>
{
console.log(res);//["bbb", "ccc", "ddd"]
let [res1,res2,res3]=res;
console.log(res1,res2,res3);//bbb ccc ddd
})
複製程式碼
Promise.race([p1,p2,……])只要有一個成功就返回
let p2= Promise.resolve('bbb');
let p3=Promise.resolve('ccc');
let p4=Promise.reject('ddd');
Promise.race([p2,p3,p4]).then(res=>
{
console.log(res);
}).catch(err=>{
console.log(err);
})//結果是bbb
複製程式碼
Promise用於資料互動
let status=1;
let userLogin = (resolve,reject)=>{
setTimeout(()=>{
if(status == 1){
resolve({data:'xxxxx',msg:'ccc',token:'xahoagoa'});
}else{
reject("shibaile");
}
},2000);
};
let getUserInfo = (resolve,reject)=>{
setTimeout(()=>{
if(status == 1){
resolve({data:'獲取使用者資訊成功',msg:'梭梭醬',token:'tiaotiaohou'});
}else{
reject('lose');
}
},1000);
}
new Promise(userLogin).then(res=>{
console.log(res);//{data:'獲取使用者資訊成功',msg:'梭梭醬',token:'tiaotiaohou'}
console.log('使用者登入成功');
return new Promise(getUserInfo);
}).then(res=>{
console.log('獲取使用者資訊成功');
console.log(res);
})
複製程式碼