Solved: Why Async/Await does not work with .forEach

The Problem

Javascript offers a number of different ways to iterate over an array. Recently while using the array.forEach syntax, I came across some interesting behaviour when using them with the async/await syntax.

To demonstrate. Lets take the following Javascript code which simply prints some messages to the console every 2 seconds.

Javascript Icon
function waitForTwoSecs(i) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(`loop iteration ${i}`); 
      resolve('resolved');
    }, 2000);
  });
}

async function mainProgram() {
  const loopIterations = [1, 2, 3];
  console.log('mainProgram Start');

  loopIterations.forEach(async iteration =>  {
    const result = await waitForTwoSecs(iteration);
  });

  console.log('mainProgram finished'); 
}

mainProgram();
Continue reading