Member-only story
JavaScript Async/Await Pitfalls With ForEach
Build bug-free apps
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…