javascript - Async await 代码在 forEach 中的运行方式不同
我有这段代码,当我运行它时,它会按顺序运行‘one’和‘two’。
所以下面的代码运行良好。
(async () => {
await runit('one').then(res => {
console.info(res);
});
await runit('two').then(res => {
console.info(res);
});
})();
现在,我想做同样的事情,但改为在循环中,所以我做了这个:
const arr = ['one', 'two'];
arr.forEach(element => {
(async () => {
await runit(element).then(res => {
console.info(res);
});
})();
});
虽然看起来代码是相同的,但它不再按照顶部代码的顺序运行。
我该如何修复这个?
答案#1
你可以使用 promise.all 函数像下面这样实现相同的功能。
const arr = ['one', 'two'];
const promises = [];
arr.forEach(element => {
promises.push(runit(element));
});
Promise.all(promises).then(results => {
console.log(results)//you will get results here.
});
答案#2
它不会等待,因为你执行的函数是异步的,你实际上是在告诉它不要等待。要解决这个问题,你可以使用简单的 for 循环:
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
await runit(item).then(res => {
console.info(res);
});
}
或者你可以使用 map 和 Promise.all:
const promises = arr.map(item => runit(item)));
const values = Promise.all(promises);
values.forEach(res => console.info(res))
后者更受欢迎。
