DEV Community

Cover image for How to use async/await inside for loop in JavaScript
Rajesh Royal
Rajesh Royal

Posted on

How to use async/await inside for loop in JavaScript

There will be a time when you would want to run async operations inside for loops (ex. API calls).

In this article, we will discuss the possible approach to combine async/await and iterative logic. Let’s take a look at how we can implement it in practice.

We are going to use - for await...of

Below is the code which shows how the API calls inside a for loop can be performed.

let urls = [
"https://jsonplaceholder.typicode.com/todos/1",
"https://jsonplaceholder.typicode.com/todos/2"
]

async function makeAPICalls() {
    for await(const url of urls){
        console.log("Api call started for - ");

        let result = await fetch(url).then(res=> res.json());
        console.log("Result = ", result);

        console.log("Api call ended for - ");
    }
}

makeAPICalls();
Enter fullscreen mode Exit fullscreen mode

Output

VM294:1 Api call started for - 
VM294:2 Promise {<pending>}
VM294:5 Result =  {userId: 1, id: 1, title: 'delectus aut autem', completed: false}
VM294:7 Api call ended for - 

VM294:3 Api call started for - 
VM294:5 Result =  {userId: 1, id: 2, title: 'quis ut nam facilis et officia qui', completed: false}
VM294:7 Api call ended for - 
Enter fullscreen mode Exit fullscreen mode

 

There are many better ways, this is just another example you may want to use.

Top comments (0)