Promise Pool With Ordered Results

Run many async tasks with a fixed concurrency limit while keeping results in input order and rejecting invalid pool sizes.

JavascriptResilience

Code

javascriptsnippet
22 lines
export function mapPool(items, mapper, concurrency = 4) {
  if (!Array.isArray(items)) throw new TypeError("items must be an array");
  if (typeof mapper !== "function") throw new TypeError("mapper must be a function");
  if (!Number.isInteger(concurrency) || concurrency < 1) {
    throw new RangeError("concurrency must be a positive integer");
  }

  const results = new Array(items.length);
  let nextIndex = 0;

  async function worker() {
    while (nextIndex < items.length) {
      const index = nextIndex;
      nextIndex += 1;
      results[index] = await mapper(items[index], index);
    }
  }

  const workerCount = Math.min(concurrency, items.length);
  const workers = Array.from({ length: workerCount }, () => worker());
  return Promise.all(workers).then(() => results);
}

Inside the snippet

Structurally, expect the functions mapPool and worker and nothing else.

The file repeats itself only inside while (nextIndex < items.length). Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. When the guard condition holds, TypeError and RangeError is thrown rather than a bogus value returned.

Points of care

  • The guard typeof mapper !== "function" short-circuits the flow with an early throw when its condition holds.

Using it

The primary signature is export function mapPool(items, mapper, concurrency = 4)

mapPool is what another module would consume; nothing else here is load-bearing for callers.

Key statements

return Promise.all(workers).then(() => results);
if (typeof mapper !== "function") throw new TypeError("mapper must be a function");
if (!Array.isArray(items)) throw new TypeError("items must be an array");

Interactive Tools for This Topic

FAQ

What happens if the preconditions do not hold?
The code refuses to continue: `TypeError` and `RangeError` is thrown while the state is still recoverable.
Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `mapPool`, `worker` at load time.