PREP WITH PROOF
Menu
JAVASCRIPT & ASYNC WORKFLOWS / PRACTICAL GUIDE

JavaScript Async Map with a Concurrency Limit: Ordered Results

Build and test a bounded async mapper that preserves input order, stops scheduling after failure and drains active work. Includes executable Node.js labs.

THE QUICK ANSWER

To limit async mapping, schedule mapper invocations rather than aggregating an array of work that has already started. A small worker pool can reserve input indices, await one operation per slot and return ordered results. Define separately whether failures stop queued work, cancel active calls or wait for them to settle.

The missing control is when each operation starts

A batch of document IDs needs enrichment from an external service. Mapping every ID to an async callback looks concise, but a large input can start far more requests than the service or client can comfortably handle. Waiting for the resulting promises does not retroactively control those starts. The scheduling decision must happen before each mapper invocation.

This guide implements a small worker pool for a finite array. It preserves input order in the returned results, keeps at most a chosen number of mapper calls unsettled, and stops assigning new items after it observes a failure. Already running calls are drained before the batch rejects. Those are explicit application choices that you can inspect and test.

The existing Promise.all versus Promise.allSettled guide explains aggregate failure policies. Here the primary task is building and checking the scheduler around the mapper. The examples use local promises and manually released gates, so their claims concern scheduling behavior rather than remote API throughput or production performance.

First fix the array-of-promises mistake

Array.prototype.map calls its callback and stores each returned value. With an async callback, those values are promises. Awaiting the array itself leaves those member promises inside the array; it does not recursively await every element. The short executable example makes the distinction visible without involving a network.

Promise.all is appropriate when all mapped results are required and starting the entire small batch is acceptable. It does not accept a concurrency limit. Passing already created promises to a limiter is also too late when their operations began during construction. Give a scheduler input values and a function it can invoke later.

import assert from 'node:assert/strict';
const pending = [1, 2, 3].map(async value => value * 2);
const stillAnArray = await pending;
assert.equal(stillAnArray, pending);
assert.equal(stillAnArray[0] instanceof Promise, true);
assert.deepEqual(await Promise.all(pending), [2, 4, 6]);
console.log('PASS: await an array does not aggregate its members');

Source: ECMAScript: Array.prototype.map algorithm ↗

Specify the scheduler contract before writing the loop

The implementation accepts an ordinary dense array, an integer limit from 1 through 1000, and a mapper receiving value and index. It snapshots array values before invoking any mapper. This is a shallow snapshot: later replacement of an input slot does not change that queued value, but mutation of a referenced object remains visible.

Sparse arrays are rejected rather than silently changing their meaning. The helper is deliberately narrower than native map: it is not a generic array-like method, does not preserve holes, and does not supply native map’s third callback argument or thisArg. Avoid proxies, accessors and mutation during input collection; use plain data arrays for this contract.

The limit counts mapper invocations whose returned work has not settled. A mapper that launches three requests at once can therefore exceed that number of underlying requests. Return and await the entire operation the slot is supposed to cover, including body reads, parsing or cleanup that belongs to completion.

DecisionThis implementationPractical consequence
Result orderInput index orderFast later items do not shift identities
FailureFirst reason observed by the schedulerLater reasons do not replace it
Pending workStop scheduling after observing failureEarlier successful effects are retained
Running workDrain before rejectingA never-settling call can keep the batch pending

A bounded mapper with ordered results and failure draining

Save this function in map-limit.mjs, adding export before async if you want to import it elsewhere. Each worker reserves an index synchronously, invokes the mapper, and awaits that result before reserving another. The shared index is used by workers in the same JavaScript execution context; there is no cross-thread shared-memory protocol here.

Results are written to their reserved index rather than pushed on completion. The number of worker loops is the smaller of the limit and input length. This bounds active mapper calls while allowing a free worker to take the next item without waiting for an entire fixed-size chunk to finish.

The catch records a separate failed flag because a rejection reason can itself be undefined, null or another falsy value. Worker loops absorb item failures, finish their current await, and return. Promise.all joins those loops; the helper then throws the saved reason. Consequently its aggregate does not reject until active work has settled.

async function mapLimit(items, limit, mapper) {
  if (!Array.isArray(items)) throw new TypeError('items must be an array');
  if (!Number.isInteger(limit) || limit < 1 || limit > 1000) {
    throw new RangeError('limit must be an integer from 1 to 1000');
  }
  if (typeof mapper !== 'function') throw new TypeError('mapper must be a function');
  // Ordinary dense arrays only; snapshot values before invoking any mapper.
  const input = new Array(items.length);
  for (let i = 0; i < input.length; i++) {
    if (!Object.hasOwn(items, i)) throw new TypeError('sparse arrays are unsupported');
    input[i] = items[i];
  }
  const output = new Array(input.length);
  let next = 0;
  let failed = false;
  let firstError;
  async function run() {
    while (!failed && next < input.length) {
      const index = next++;
      try {
        output[index] = await mapper(input[index], index);
      } catch (error) {
        if (!failed) {
          failed = true;
          firstError = error;
        }
      }
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, input.length) }, () => run()));
  if (failed) throw firstError;
  return output;
}

Source: ECMAScript: Promise.all and PerformPromiseAll ↗

Test ordering and failure without guessing timer durations

Paste the function above into a fresh .mjs file with this lab below it, then run node your-file.mjs. Alternatively export the function and import it, replacing the comment. The lab was executed on Node.js 24.22.1. It uses Node’s setImmediate promise to let the queued continuations run after each controlled gate release.

The first scenario starts only indices 0 and 1. It releases item 1, then item 2, while item 0 remains pending. This verifies that the scheduler reuses free capacity and still returns values in input order. The active counter measures the precise unit promised by the contract.

The second scenario rejects one of two running items while holding the other open. No later item starts, and the outer result remains pending until the held item finishes. A rejection handler is attached before triggering failure so the test itself does not create an unobserved rejected batch.

import assert from 'node:assert/strict';
import { setImmediate as turn } from 'node:timers/promises';
// Paste mapLimit above this block, or import it from your own module.
function deferred() {
  let resolve, reject;
  const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
  return { promise, resolve, reject };
}

const gates = Array.from({ length: 4 }, deferred);
const started = [];
let active = 0, peak = 0;
const job = mapLimit([10, 20, 30, 40], 2, async (value, index) => {
  started.push(index);
  active++;
  peak = Math.max(peak, active);
  try { await gates[index].promise; return value * 2; }
  finally { active--; }
});
assert.deepEqual(started, [0, 1]);
gates[1].resolve(); await turn();
assert.deepEqual(started, [0, 1, 2]);
gates[2].resolve(); await turn();
assert.deepEqual(started, [0, 1, 2, 3]);
gates[3].resolve(); gates[0].resolve();
assert.deepEqual(await job, [20, 40, 60, 80]);
assert.equal(peak, 2);
assert.equal(active, 0);

const hold = deferred();
const bad = deferred();
const calls = [];
const boom = new Error('item failed');
let finished = false;
const failedJob = mapLimit([0, 1, 2, 3], 2, (_, index) => {
  calls.push(index);
  return index === 0 ? hold.promise : bad.promise;
});
// Attach a rejection handler immediately, before triggering the failure.
const observed = failedJob.then(
  () => { finished = true; return { ok: true }; },
  reason => { finished = true; return { ok: false, reason }; }
);
bad.reject(boom); await turn();
assert.deepEqual(calls, [0, 1]);
assert.equal(finished, false); // still draining item 0
hold.resolve('already running');
const outcome = await observed;
assert.equal(outcome.ok, false);
assert.equal(outcome.reason, boom);
assert.deepEqual(calls, [0, 1]);
console.log('PASS: ordered results, active cap, stopped scheduling and drain');

Source: Node.js: timers promises setImmediate ↗

Validate empty inputs, sparse arrays and unusual failures

The following checks can run in another file with the same function. A valid empty batch resolves to an empty array without invoking the mapper. Limit validation still applies to empty input, making configuration errors visible consistently. Successful zero, false and undefined values must not be mistaken for failure.

A synchronous throw from a mapper follows the same item-failure path as an asynchronous rejection. The explicit undefined rejection test protects the failed-flag design: checking if(firstError) would incorrectly report success for that case. These checks also distinguish an absent array element from an element whose stored value is undefined.

import assert from 'node:assert/strict';
// Paste mapLimit above this block, or import it from your own module.
assert.deepEqual(await mapLimit([], 3, value => value), []);
assert.deepEqual(await mapLimit([0, false, undefined], 1, value => value),
  [0, false, undefined]);
await assert.rejects(mapLimit([1], 0, value => value), RangeError);
await assert.rejects(mapLimit(new Array(2), 1, value => value), TypeError);
const sentinel = { kind: 'synchronous failure' };
await assert.rejects(mapLimit([1], 1, () => { throw sentinel; }),
  reason => reason === sentinel);
let rejected = false;
try { await mapLimit([1], 1, () => Promise.reject(undefined)); }
catch (reason) { rejected = true; assert.equal(reason, undefined); }
assert.equal(rejected, true);
console.log('PASS: empty input, falsy values, invalid options and rejection reasons');

A stop policy is not cancellation or a transaction

The scheduler stops assigning items only after its catch observes failure. Another worker may already have started an item before that observation. Do not describe this as an instantaneous global stop, and do not assume the failing input index is the smallest index that can appear in a failure.

Draining is useful when the caller must avoid starting a replacement batch while old work is still running. Its cost is waiting for every active mapper to settle. If a mapper can hang indefinitely, design supported operation deadlines and cancellation before relying on this helper as a lifecycle boundary.

An AbortController can communicate an abort request to APIs that support its signal. This implementation does not create one or cancel active operations. Adding cancellation requires deciding how the mapper receives the signal and how cleanup settles. A client-side rejection also does not undo a remote write that already succeeded.

Retrying the entire rejected batch can repeat successful side effects. For writes, preserve operation identities and use an appropriate idempotency or reconciliation policy. The helper intentionally returns no partial-success report; if independent outcomes are needed, design a result record per item or choose a tested queue with that contract.

Source: Node.js: AbortController and AbortSignal ↗

Choose a limit using the bottleneck you can measure

A simultaneous-work cap is different from a requests-per-second quota. Two very fast slots can still produce a high request rate. Time-based quotas, retry delays and shared limits across multiple processes require additional scheduling. Ten batches with limit four can create forty active mapper calls; the cap belongs to one invocation.

This helper keeps a full input snapshot and full output array, so its memory use grows with batch size even though active work is bounded. For a huge export or an unbounded stream, use a design with incremental input, backpressure and a defined output buffer. Preserving strict output order can itself require buffering later completions.

A chunked approach is simpler when chunk barriers are desirable: finish one group before starting another. A worker pool uses freed slots sooner when durations differ. Neither choice guarantees faster execution for CPU-heavy synchronous JavaScript; promises do not create extra JavaScript threads. Measure latency, resource use and service errors with representative work before increasing the cap.

Keep the completion boundary visible to callers

Before using this pattern in an integration, test four things with the real mapper: what starts, what counts as complete, what happens after failure, and what may already have changed. Include an empty batch, a slow first item, a later rejection, a synchronous throw and cleanup that must finish before a retry.

Use ordinary Promise.all for small independent groups when unrestricted starts are acceptable, sequential iteration when dependencies require it, and a bounded scheduler when active work must be controlled. For this implementation, input order, a per-batch concurrency cap and drain-before-reject are the useful guarantees. Keep those guarantees separate from rate limiting, cancellation and rollback.

KEEP THESE THREE THINGS

Your next steps

  1. A concurrency cap controls when mapper calls start; Promise.all alone supplies no limit.
  2. Write results by input index and define the complete operation represented by each slot.
  3. Stop scheduling, draining, cancellation, rate limiting and rollback are separate policies.

Sources & official resources

Linked resources checked on 2026-11-07. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →