Fetch many URLs with a concurrency limit
Fetch many URLs with a concurrency limit in JavaScript: workers share one iterator and each takes the next URL. Node.js 24 and browsers.
Fifty URLs should not become fifty simultaneous requests. A few workers can share one iterator over the list, and each takes the next URL when it is free.
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
async function fetchAll(urls, limit, load = fetch) {
const results = new Array(urls.length);
const queue = urls.entries();
const worker = async () => {
for (const [i, url] of queue) {
results[i] = await (await load(url)).text();
}
};
await Promise.all(Array.from({ length: limit }, worker));
return results;
}
let active = 0;
let peak = 0;
const fakeLoad = async (url) => {
peak = Math.max(peak, ++active);
await delay(10);
active--;
return { text: async () => url.toUpperCase() };
};
console.log(await fetchAll(['/a', '/b', '/c', '/d', '/e'], 2, fakeLoad));
console.log('peak', peak);[ '/A', '/B', '/C', '/D', '/E' ]
peak 2urls.entries() is an iterator, and an iterator is consumed once: when one worker takes [2, '/c'], no other worker can get it. That removes the need for a counter. The results are stored by index, so they keep the order of the input.
Two requests were in flight at the peak, never more. If one request throws, that worker stops and the whole Promise.all rejects; wrap the body in try when failures are acceptable.