DEV Community

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

Posted on

6 3

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay