JavaScriptFundamental (ES6), part 2
Async map with a concurrency limit in JavaScript
21 Map with a concurrency limit
hardWrite mapLimit(items, limit, worker) that runs at most limit workers at once, keeps the results in input order, and rejects like Promise.all if a worker throws. Measure the peak concurrency and prove it never exceeds the limit.
Stuck? Three hints, smallest first
- 1. Start
limitidentical runners. Each one takes the next unclaimed index until there are none left. - 2. A shared
nextcounter, read and incremented in one synchronous step, is all the co-ordination you need. - 3. Write into
results[index], not withpush, or the order follows completion instead of input.
async function mapLimit(items, limit, worker) {
const results = new Array(items.length);
let next = 0;
const runner = async () => {
while (next < items.length) {
const index = next++; // claimed synchronously: no two runners share one
results[index] = await worker(items[index], index);
}
};
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, runner));
return results;
}
let active = 0;
let peak = 0;
const upload = async (n) => {
active++;
peak = Math.max(peak, active);
await Promise.resolve();
await Promise.resolve();
active--;
return n * 2;
};
const doubled = await mapLimit([1, 2, 3, 4, 5, 6, 7], 3, upload);
const sequential = [];
await mapLimit([1, 2, 3], 1, async (n) => {
sequential.push('start ' + n);
await Promise.resolve();
sequential.push('end ' + n);
});
const failed = await mapLimit([1, 2, 3], 2, async (n) => {
if (n === 2) throw new Error('item 2 failed');
return n;
}).then(() => 'resolved', (e) => e.message);
console.log('results :', doubled);
console.log('peak :', peak, 'of a limit of 3');
console.log('limit 1 :', sequential);
console.log('failure :', failed);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('every item is processed', doubled, [2, 4, 6, 8, 10, 12, 14]);
test('results stay in input order', doubled.at(-1), 14);
test('never more than the limit at once', peak, 3);
test('a limit of one is strictly sequential', sequential, ['start 1', 'end 1', 'start 2', 'end 2', 'start 3', 'end 3']);
test('a limit above the item count starts only as many runners as there are items', await mapLimit([1, 2], 10, upload), [2, 4]);
test('an empty list resolves without starting a worker', await mapLimit([], 3, upload), []);
test('the worker sees the index too', await mapLimit(['a', 'b'], 2, async (v, i) => v + i), ['a0', 'b1']);
test('one failure rejects the whole thing, like Promise.all', failed, 'item 2 failed');
The trick is that the runners are identical and stateless: each one loops "claim an index, do it, repeat" and they all stop when the indexes run out. There is no scheduler, no queue object and no bookkeeping of which worker is free. const index = next++ is atomic in the only sense that matters here — JavaScript runs one thing at a time, so no two runners can read the same value.
peak === 3 is the assertion the whole exercise exists for. Without it this is a plausible-looking function you have to trust; with it, the claim is checked. Note how the measurement works: increment on entry, take the maximum, decrement on exit. That is the shape of every concurrency probe you will write.
Two honest limitations. Failure behaves like Promise.all, so the first rejection wins and the runners already in flight keep going — there is no cancellation, only an ignored result. And "in order" applies to the results, not the completions: item 7 may finish before item 3, and results[6] = ... is what keeps the array honest. Swap it for results.push and the bug survives every test that does not check order.