The Pitfalls of Async/Await in Array Loops
Using async
/await
while looping through arrays in Javascript loop seems simple, but there’s some non-intuitive behavior to look out for when combining the two. Let’s take a look at three different examples to see what you should look out for, and which loop is best for specific use cases.
forEach
If you only take one thing away from this article, let it be this: async
/await
doesn’t work in Array.prototype.forEach
. Let’s dive into an example to see why:
Finished!
Received Todo 2, Response: { ··· }
Received Todo 1, Response: { ··· }
Received Todo 3, Response: { ··· }
⚠️ Problem 1:
The code above will happily execute. However, notice that Finished!
was logged out first despite our use of await
before urls.forEach
. The first problem is that you can’t await
the entire loop when using forEach
.
⚠️ ️Problem 2:
In addition, despite the use of await
within the loop, it didn’t wait for each request to finish before executing the next one. So, the requests were…