JavaScript

Limit concurrent asynchronous jobs

Use a small worker pool when a list of asynchronous jobs should run concurrently without starting every job at once. Each worker takes the next available index and stores the result in the original position.

Worked example

Node.js example · save as example.mjs and run node example.mjs

async function mapLimit(items, limit, work) {
  if (!Number.isInteger(limit) || limit < 1) throw new Error("Invalid limit");
  let next = 0;
  const results = new Array(items.length);
  await Promise.all(Array.from({length: Math.min(limit, items.length)}, async () => {
    while (next < items.length) {
      const index = next++;
      results[index] = await work(items[index]);
    }
  }));
  return results;
}
console.log(JSON.stringify(await mapLimit([1, 2, 3], 2, async n => n * 2)));

How it works

Workers claim indices synchronously before awaiting work, so they do not process the same item twice in this single-threaded JavaScript execution model. Results are written by index, preserving input order even when job completion order differs.

Limits and mistakes

If one job rejects, other active workers are not automatically canceled and may continue. This example is for a finite in-memory list, not an unbounded production queue. Add explicit cancellation and per-job error handling when partial completion matters.

Check the result

Expect [2,4,6]. Instrument active jobs and verify the maximum never exceeds the chosen limit. Test an empty list and a rejected job before using the helper for external requests.

Sources

Reference documentation for the behavior used in this guide: