Async Await map not awaiting async function to complete inside map function before mapping next item

.map() is not async or promise aware. It just dutifully takes the value you return from its callback and stuffs it in the result array. Even though it’s a promise in your case, it still just keeps on going, not waiting for that promise. And, there is nothing you can do in that regard to change the .map() behavior. That’s just the way it works.

Instead, use a for loop and then await your async function inside the loop and that will suspend the loop.


Your structure:

await Promise.all(array.map(item => anAsyncFunction(item)));

is running all the anAsyncFunction() calls in parallel and then waiting for all of them to finish.


To run them sequentially, use a for loop and await the individual function call:

const fn = async() => {
  const array = [0, 1, 2];
  console.log('begin');
  for (let item of array) {
      await anAsyncFunction(item);
  }
  console.log('finished');
  return;
}

This is an important thing to know that none of the array iteration methods are async aware. That includes .map(), .filter(), .forEach(), etc… So, if you want to await something inside the loop in order to sequence your async operations, then use a regular for loop which is async aware and will pause the loop.

Leave a Comment