Skip to content
GreenSnippets

Run async tasks with a concurrency limit

Process a large list with at most N promises in flight at once, preserving result order.

JavaScript
async function mapPool(items, limit, worker) {
  const results = new Array(items.length);
  let next = 0;
  async function run() {
    while (next < items.length) {
      const index = next++;
      results[index] = await worker(items[index], index);
    }
  }
  const workers = Array.from({ length: Math.min(limit, items.length) }, run);
  await Promise.all(workers);
  return results;
}

Example / expected output

Output
await mapPool(urls, 5, (url) => fetch(url).then((r) => r.status));

How it works

Promise.all on thousands of items fires them all at once, which can exhaust sockets or hit rate limits. This pool starts limit workers that pull the next item from a shared index. Results keep the input order, and the first error rejects the whole call.