javascript 26 lines · 7 steps

Bounded-concurrency async map in JavaScript

Run a worker over many items with a fixed number of tasks in flight, preserving result order.

Explained by highlit
1async function mapWithConcurrency(items, limit, worker) {
2 const results = new Array(items.length);
3 let nextIndex = 0;
4 
5 async function runner() {
6 while (true) {
7 const current = nextIndex++;
8 if (current >= items.length) return;
9 results[current] = await worker(items[current], current);
10 }
11 }
12 
13 const pool = Array.from({ length: Math.min(limit, items.length) }, runner);
14 await Promise.all(pool);
15 return results;
16}
17 
18async function mapSettledWithConcurrency(items, limit, worker) {
19 return mapWithConcurrency(items, limit, async (item, index) => {
20 try {
21 return { status: 'fulfilled', value: await worker(item, index) };
22 } catch (reason) {
23 return { status: 'rejected', reason };
24 }
25 });
26}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A shared mutable index lets a fixed set of workers pull tasks without overlapping.
  2. 2Writing results by original index keeps output order independent of completion order.
  3. 3Wrapping each worker in try/catch turns a fail-fast map into an allSettled-style one.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Bounded-concurrency async map in JavaScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code