Promise.all([fn(),fn()]) 都返回resolve(); 才能够拿到成功的返回值
Promise.all([fn(),fn()]) 有一个返回reject(), 则进入catch(error), 拿到失败的返回值

Promise.all 使用方法_javascript


Promise.all 使用方法_返回结果_02

1.await 可以获得多个promise 的返回结果

  1. Promise.all 返回的也是promise,所以可以直接await Promise.all();

1. 使用Promise

function fn(){
return new Promise((resolve,reject)=>{
let randomNum = parseInt(Math.random()*6+1);
console.log(randomNum);
if(randomNum>3){
resolve('买');
}
else{
reject('不买');
}
})
}

Promise.all([fn(),fn()]).then((x)=>{console.log(x,'success')},(y)=>{console.log(y,'error');});

Promise.all 使用方法_Math_03

使用await

await 是可以获得多个promise 返回结果的,Promise.all()返回的也是promise结果。所以想要使用await 拿到多个promise的返回值,可以直接await Promise.all();

function fn(){
return new Promise((resolve,reject)=>{
let randomNum = parseInt(Math.random()*6+1);
console.log(randomNum);
if(randomNum>3){
resolve('买');
}
else{
reject('不买');
}
})
}
async function test(){
try{
let res = await Promise.all([fn(),fn()]);
console.log(res,'success');
}
catch(error){
console.log(error,'error');
}
}

test();
await Promise.all(arr.map((item) => geo.getLocation(item.lon, item.lat).then(address => item.address = address)));
let res = await Promise.all([
checkIDNumber(this.driverObj.driverId, IDNumber),
certificate(this.driverObj.driverId, this.driverObj.certificate)]);
res.forEach(p => p&&!p.flag && p.msg && this.$message.error(p.msg))
return res.every(p => p ? p.flag : 1);
},
return Promise.all(allPromise)
.then(arr => arr.flat())
.catch(() => []);
}
Promise.all(query).then(() => {
this.animationDuration = `${this.textWidth / this.speed}s`
this.animationDelay = `-${this.boxWidth / this.speed}s`
setTimeout(() => {
this.animationPlayState = 'running'
}, 1000)
})
switch (type) {
case 'left':
Promise.all([
this.move(this.selector, leftWidth),
this.move(this.leftButton, 0),
this.move(this.rightButton, rightWidth * 2)
]).then(() => {
this.setEmit(leftWidth, type)
})
break
case 'right':
Promise.all([
this.move(this.selector, -rightWidth),
this.move(this.leftButton, -leftWidth * 2),
this.move(this.rightButton, 0)
]).then(() => {
this.setEmit(-rightWidth, type)
})
break
default:
Promise.all([
this.move(this.selector, 0),
this.move(this.leftButton, -leftWidth),
this.move(this.rightButton, rightWidth)
]).then(() => {
this.setEmit(0, type)
})

}