Bounded Concurrency Promise Pool

Run an array of async tasks with a maximum concurrency, so a large batch does not open all connections at once and overwhelm a downstream service.

JavascriptResilience

Code

javascriptsnippet
17 lines
export async function pool(items, worker, concurrency) {
  if (concurrency < 1) throw new RangeError("concurrency must be >= 1");
  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 runners = [];
  for (let i = 0; i < Math.min(concurrency, items.length); i++) {
    runners.push(run());
  }
  await Promise.all(runners);
  return results;
}

Inside the snippet

The working surface is the functions pool and run — everything else is wiring.

The core work runs in nested loops — outer while (next < items.length), inner for (let i = 0; i < Math.min(concurrency, items.length); i++). Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. A guard precedes the RangeError: bad state stops the flow there instead of continuing.

Caveats

  • The guard concurrency < 1 short-circuits the flow with an early throw when its condition holds.

Using it

The primary signature is export async function pool(items, worker, concurrency)

Import pool from the file and call it — the rest of the code is implementation detail.

Key statements

await Promise.all(runners);
if (concurrency < 1) throw new RangeError("concurrency must be >= 1");
results[index] = await worker(items[index], index);

Interactive Tools for This Topic

FAQ

Does the code validate its input?
Validation comes first — `RangeError` marks the failure at `concurrency < 1`, before any partial work happens.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `pool`, `run` at load time.