等待一个 forEach 异步函数完成后继续代码

时间:2021-02-07 16:58:55

标签: javascript async-await

我举了一个简单的例子来说明我的问题:

  • 我必须在数组的每个元素上运行一个异步函数(例如 findIndex,睡眠时间为 500 毫秒)。
  • 在循环完该数组上的所有元素后,我必须删除该数组。

问题是在测试索引之前数组已经是空的(因为最后一行arr = [];)。

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
const findIndex = async function(arr, obj) {
  await timeout(500);
  return arr.findIndex(o => o.id == obj.id);
}; 

let arr = [{id:1}, {id:2}, {id:3}];

arr.forEach(async function(obj) {
   const idx = await findIndex(arr, obj);
   console.log(`Idx is ${idx}`); 
}); 

arr = [];

等待所有迭代继续进行的最佳解决方案是什么?

0 个答案:

没有答案