Promise.all on a big list starts every task at once. If each task is an HTTP call, you can hit rate limits or open too many sockets. A small worker pool fixes that in about 12 lines, with no library.
The code
async function mapLimit(items, limit, fn) { const results = new Array(items.length); let next = 0; async function worker() { while (next < items.length) { const i = next++; results[i] = await fn(items[i], i); } } const workers = Array.from({ length: Math.min(limit, items.length) }, worker); await Promise.all(workers); return results; } How it works
-
limitworkers start together. Each one pulls the next index, runs the task, then pulls again until the list is empty. -
next++runs synchronously, so two workers never take the same index. - Results are written by index, so the output keeps the input order even when tasks finish out of order.
- If one task throws,
Promise.allrejects and you get the first error. Workers already running will finish their current task, but no new ones are started by the failed worker. Wrapfnin a try/catch if you want to collect errors instead.
Usage
const urls = [/* 200 urls */]; const pages = await mapLimit(urls, 5, async (url) => { const res = await fetch(url); return res.text(); }); At most 5 requests are in flight at any time.
A test you can run
This checks two things: the order is kept, and the peak number of running tasks never goes above the limit.
const assert = require('node:assert'); const { mapLimit } = require('./pool'); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); (async () => { let running = 0; let peak = 0; const out = await mapLimit([1, 2, 3, 4, 5, 6, 7, 8], 3, async (n) => { running++; peak = Math.max(peak, running); await sleep(30 - n * 2); running--; return n * 10; }); assert.deepStrictEqual(out, [10, 20, 30, 40, 50, 60, 70, 80]); assert.strictEqual(peak, 3); console.log('ok: order kept, peak concurrency =', peak); })(); Save the function as pool.js with module.exports = { mapLimit };, save the test as test.js, and run node test.js. I ran it on Node and it printed ok: order kept, peak concurrency = 3.
When to use something else
If you also need retries, priorities or a queue that stays open, a library such as p-limit or p-queue is a better fit. For a one-off batch, this is enough.
