How to use async/await in Loops

In this article, we will show you how to use async/await in loops that you can use it with any JavaScript framework. Here we will see three different loops with examples.

Preparing an example

For the demonstration, we have to use the fake API function and data list to call an API. Check out the article if you don’t know how to integrate an API in React.

We will use the following promise function.

And consider the following list to call an API.

async/await in Loops

  1. Await in a for loop
  2. Await in a forEach loop
  3. Await with map

1. Await in a for loop

We are going to loop through the data and get the result from an fakeAPI function.

The outcome is as expected below.

Output - Await in a for loop - Clue Mediator
Output – Await in a for loop – Clue Mediator

2. Await in a forEach loop

We’ll follow the same steps as we did in the for-loop example.

This is what you could imagine the console to look like:

However, the end outcome is not as expected. Following is the order of the console logs.

Output - Await in a forEach loop - Clue Mediator
Output – Await in a forEach loop – Clue Mediator

Therefore, you can’t use await in the forEach loop. It is unable to support async and await.

3. Await with map

When you use await in a map, the result is always an array of promises. Because asynchronous functions always return promises.

You must wait for the array of promises to be resolved since map always returns promises. You may accomplish this by using the await Promise.all(arrayOfPromises).

This is what you’ll get.

Output - Await with map - Clue Mediator
Output – Await with map – Clue Mediator

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *