我举了一个简单的例子来说明我的问题:
问题是在测试索引之前数组已经是空的(因为最后一行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 = [];
等待所有迭代继续进行的最佳解决方案是什么?