0

I made a simple example of my problem:

  • I have to run an async function (for this example the findIndex, with a sleep of 500ms) on every element of an array.
  • I have to remove that array after all elements on it has been looped.

Problem is the array is already empty (because of the last line arr = [];) before the index is tested.

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 = [];

What's the best solution to wait for all iterations to continue ?

Arthur
  • 4,337
  • 3
  • 28
  • 48

0 Answers0