Fetch Multiple Urls at The Same Time
2 min read

Fetch Multiple URLs at The Same Time

Awaiting each and every request may lead to long waiting times, a quick fix it to make all requests at the same time using Promises.all().

A Bad Example

Say that we have a list of 100 requests, the normal way to iterate through and fetch would perhaps look like this.

const urls = [...];
for(const url of urls) {
    const result = await fetch(url);
    const data = await result.json();

    // handle data
    // ...
}

This will make each request separately, which might take a long time.

The Solution

We will make this much faster with Promise.all(), which fetches all URLs at the same time. There are two ways to do it.

const arrayOfResponses = await Promise.all(
    urls.map((url) =>
        fetch(url)
            .then((res) => res.json())
    )
);

Another approach could be like this;

const urls = [...];
const promises = urls.map(url => fetch(url));

await Promise.all(promises);

for (const promise of promises) {
    const data = await promise.json();

    // handle data
    // ...
}