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.
Checkout more articles on JavaScript / ReactJS
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.
1 2 3 4 5 6 7 | const fakeAPI = async (time) => { return new Promise((resolve) => { setTimeout(() => { resolve(`Response: ${time}`); }, time); }); }; |
And consider the following list to call an API.
1 | const data = [1000, 500, 2000, 5000, 3000]; |
async/await in Loops
1. Await in a for loop
We are going to loop through the data
and get the result from an fakeAPI
function.
1 2 3 4 5 6 7 8 9 10 11 12 | const forLoop = async () => { console.log('Before API Call'); for (let index = 0; index < data.length; index++) { const res = await fakeAPI(data[index]); console.log(res); } console.log('After API Call'); }; forLoop(); |
The outcome is as expected below.
2. Await in a forEach loop
We’ll follow the same steps as we did in the for-loop example.
1 2 3 4 5 6 7 8 9 10 11 12 | const forEachLoop = async () => { console.log('Before API Call'); data.forEach(async (x) => { const res = await fakeAPI(x); console.log(res); }); console.log('After API Call'); }; forEachLoop(); |
This is what you could imagine the console to look like:
1 2 3 4 5 6 7 | Before API Call Response: 1000 Response: 500 Response: 2000 Response: 5000 Response: 3000 After API Call |
However, the end outcome is not as expected. Following is the order of the console logs.
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)
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const mapLoop = async () => { console.log('Before API Call'); const promises = data.map(async (x) => { const res = await fakeAPI(x); return result; }); const result = await Promise.all(promises); console.log(result); console.log('After API Call'); }; mapLoop(); |
This is what you’ll get.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂