function getTimeOut1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('===5000ms===');
}, 5000);
});
}
function getTimeOut2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('===2000ms===');
}, 2000);
});
}
如何用async/await实现这种(分头执行)的效果:
getTimeOut1().then(res => {
console.log(res);
});
getTimeOut2().then(res => {
console.log(res);
});
- 普通的await会等a的返回结果出来再执行b ---> 8000ms+
const a = await getTimeOut1();
const b = await getTimeOut2();
- 用Promise.all([...p])的形式,虽然是并行操作,但会等最慢的一次执行完才会返回结果。---> 5000ms+
所以没有想明白如何用async/await实现常规的并行回调。
上面代码中,虽然map方法的参数是async函数,但它是并发执行的,因为只有async函数内部是继发执行,外部不受影响。后面的for..of循环内部使用了await,因此实现了按顺序输出。
希望这个答案可以帮到你,谢谢采纳意见!