目标
等待多个异步任务都完成后,再统一进行善后任务
方法一(推荐):async
let actionArr = [];
async function echo(index) {
console.log(('echo-' + index));
}
// 循环调用
for (let i = 0; i < 5; i++) {
actionArr.push(echo(i)); // 将每次循环调用的方法添加到方法数组中
}
Promise.all(actionArr).then(() => {
console.log("All done==========!");
});
方法二:Promise 对象
注:定义一个 Promise 后,最后要 resolve(),不然一直上 pending 状态
let actionArr = [];
echo = (index) => {
console.log(('echo-' + index));
}
// 循环调用
for (let i = 0; i < 5; i++) {
let action = () => { // 将每一次循环方法定义为一个方法变量
return new Promise(resolve => { // 每个方法返回一个Promise对象,第一个参数为resolve方法
echo(i)
resolve()
});
}
actionArr.push(action()); // 将每次循环调用的方法添加到方法数组中
}
Promise.all(actionArr).then(() => {
console.log("All done==========!");
});