DailyJS

JavaScript news and opinion.

Follow publication

Member-only story

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 logged out of order. If the first request takes longer than the following requests, it could still finish last.

For both of those reasons, forEach should not be relied upon if you’re using async/await.

Promise.all

Let’s solve the issue of waiting on the entire loop to finish. Since the await operation creates a promise under the hood, we can use Promise.all to await all the requests that were kicked during the loop to finish:

Received Todo 1, Response: { ··· }
Received Todo 2, Response: { ··· }
Received Todo 3, Response: { ··· }
Finished!

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

DailyJS
DailyJS
Tory Walker
Tory Walker

Written by Tory Walker

Software engineer with a passion for learning and sharing knowledge.

Responses (14)

Write a response