Published on

Javascript foreach runs await in parallel

Authors

On a piece of code I was working on there were a number of async functions. These functions operate on an array of data. The way I normally handle this is using the standard forEach function. The problem I found is that even if you await in the callback in the for loop this does not help:

const takesLongToRun = async (additionalText) => {
  setTimeout(() => {
    console.log(`Long function done :) ${additionalText}`)
  }, 3000)
}

const mainNotWorking = async () => {
  const numbers = [1, 2, 3, 4]

  numbers.forEach(async (num) => {
    console.log(num)
    await takesLongToRun(num)
  })
}

mainNotWorking()

which outputs:

1
2
3
4
Long function done :) 1
Long function done :) 2
Long function done :) 3
Long function done :) 4

So the functions do run in order but the code before the call is all run then the functions are called. What I expected rather was:

1
Long function done :) 1
2
Long function done :) 2
3
Long function done :) 3
4
Long function done :) 4

After doing a bit of googling I found that this is an issue with forEach and instead the for of syntax which allows this. I changed my code as below:

const mainWorking = async () => {
  const numbers = [1, 2, 3, 4]
  for (const num of numbers) {
    console.log(num)
    await takesLongToRun(num)
  }
}

This outputs the expected result.