Member-only story

JavaScript Async/Await Pitfalls With ForEach

Johannes Baum
Better Programming
Published in
2 min readFeb 26, 2021

--

Rubik’s cube
Photo by ALAN DE LA CRUZ on Unsplash.

A common pitfall in JavaScript is the usage of async/await in combination with forEach. Let’s look at an example with a simple asynchronous function (asyncPrint) that prints a value to the console. Say we want to call it sequentially for every value in an array via forEach:

We might expect the following output:

1
2
3

However, it does not work like that. We can point out the problem by implementing asyncPrint with a random delay before printing. If you run the snippet a couple of times, you will observe that the output occurs in any random order:

What Is the Problem?

forEach expects a synchronous function. This means that it will not wait for our passed asynchronous…

--

--

Johannes Baum
Johannes Baum

Written by Johannes Baum

Creator of GridEngine (https://github.com/Annoraaq/grid-engine) 👾 Software Engineer 🚀 JavaScript/TypeScript

Write a response