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
- JavaScript Interview Questions and Answers
- How to use async functions in useEffect
- How to validate a radio button in React
- Dialog boxes in JavaScript
- How to render HTML in React
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.
const fakeAPI = async (time) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(`Response: ${time}`);
}, time);
});
};
And consider the following list to call an API.
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.
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.
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.
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:
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.
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)`.
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.
Output - Await with map - Clue Mediator
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐