Skip to content
jshacks.dev
Async

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.

1 min read
Summarize in AI

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.

JavaScript
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);
Text
[ '/A', '/B', '/C', '/D', '/E' ]
peak 2

urls.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.

Also inBrowser
Taggednode 24
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.