JavaScript

How to Make Asynchronous Requests in a Loop in JavaScript

Last updated: 10.10.2025
Views: 250

Implementing asynchronous requests inside a JavaScript loop may not seem obvious at first. When making asynchronous requests inside a JavaScript loop, it is important to handle them correctly. This can be done in different ways. In this post, we will look at 2 ways.

Parallel Requests with Promise.all() (Fastest)

If the requests are independent and can be executed in parallel, use Promise.all(). This allows all requests to run simultaneously, improving performance.

JavaScript

const ids = [12, 23, 45, 57];

async function fetchAllData() {
    const responses = await Promise.all(
        ids.map((id) => {
            const url = 'https://api.example.com/some/' + id;
            return fetch(url).then(res => res.json());
        })
    );
    console.log(responses); // Array of resolved responses
}

fetchAllData();

Best for: Faster execution when requests do not depend on each other.

Sequential Requests with for...of (Ensures Order)

If requests must be executed one after another, use for...of with await.

JavaScript

const ids = [12, 23, 45, 57];

async function fetchSequentially() {
    for (const id of ids) {
        const url = 'https://api.example.com/some/' + id;
        const response = await fetch(url);
        const data = await response.json();
        console.log(data); // Logs each response one by one
    }
}
 
fetchSequentially();

Best for: When requests depend on previous results or must be executed in order.

author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

One response to “How to Make Asynchronous Requests in a Loop in JavaScript”

  1. tlover tonet says:

    With every little thing that appears to be building throughout this particular subject matter, a significant percentage of opinions happen to be somewhat stimulating. Having said that, I am sorry, because I do not subscribe to your entire theory, all be it refreshing none the less. It appears to everyone that your comments are actually not totally validated and in reality you are yourself not even wholly convinced of your assertion. In any case I did appreciate examining it.

Leave a Reply

Your email address will not be published. Required fields are marked *