A promise pool in 15 lines: run async tasks with a concurrency limit
Promise.all fires everything at once. That's fine for five requests and a disaster for five thousand: you hit rate limits, exhaust sockets, or get your IP throttled.
What you usually want is "run these, but at most N at a time". Here's a tiny, dependency-free way to do it.
async function promisePool(tasks, limit) {
if (!Number.isInteger(limit) || limit < 1) throw new RangeError('limit must be >= 1');
const results = new Array(tasks.length);
let next = 0;
async function worker() {
while (next < tasks.length) {
const i = next++;
results[i] = await tasks[i]();
}
}
const workers = Array.from({ length: Math.min(limit, tasks.length) }, worker);
await Promise.all(workers);
return results;
}
How it works
Instead of a queue and callbacks, we start limit workers. Each worker is a loop that grabs the next index and awaits that task. When a task finishes, the worker immediately takes the next one, so there are always up to limit tasks in flight.
Why is next++ safe without locks? JavaScript runs your code on a single thread. The read-and-increment happens synchronously between awaits, so two workers can never grab the same index.
Results are written by index, so the output order matches the input order, even if task 3 finishes before task 1.
Using it
const urls = [ /* ...hundreds of URLs... */ ];
const tasks = urls.map((u) => () => fetch(u).then((r) => r.status));
const statuses = await promisePool(tasks, 5);
Note that we pass functions that return promises, not promises. A promise starts running the moment it's created, so urls.map((u) => fetch(u)) would fire everything immediately and defeat the limit.
Tests
I tested it with Node's built-in runner (node --test):
- output keeps input order even when durations differ;
- the number of active tasks peaks at exactly the limit;
- an empty list returns
[]; - a failing task rejects the whole pool;
- a limit below 1 throws a
RangeError.
Trade-offs
- Fail-fast: if one task throws, the pool rejects, but tasks already running keep going. If you'd rather collect every outcome, wrap each task so it returns
{ ok, value | error }, the same idea asPromise.allSettled. - No cancellation: pair it with an
AbortControllerif you need to stop early. - For retries, queues with priorities or rate limits per second, a library like
p-limitorbottleneckis worth it.
For a script that just needs to be polite to an API, 15 lines will do.
What's your go-to pattern for this? Let me know in the comments.
Comments
No comments yet. Start the discussion.