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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs