05

Async pool (concurrency limit)

25 min·senior·

Implement asyncPool(limit, items, fn) that:

  • Runs fn(item) for every item, with at most limit running concurrently
  • Resolves to an array of results in the same order as input
  • If any task rejects, the whole pool rejects (fast-fail OK; bonus: cancel inflight)
await asyncPool(2, [1, 2, 3, 4], async (n) => {
  await sleep(n * 10);
  return n * 2;
});
// → [2, 4, 6, 8]
expected time · O(n) tasks
expected space · O(concurrency)
4 lines
⏵ run · no run yet · ctrl+enter