First ask which scheduling they want, because two things get called this. A sliding window keeps limit calls running: the moment one finishes, the next item starts. Fixed chunks run limit items with Promise.all, wait for all of them, then run the next chunk; it's shorter but a slow item holds up its chunk. The sliding window is the usual answer: start limit workers that each pull the next index from a shared counter, write each result at its own index so the output keeps the input order, and wait for the workers with Promise.all. Then harden it: stop starting new work after a failure, reject a bad limit, and offer an all-settled mode and an AbortSignal.
Implement concurrency-limited async mapping. One earlier interview required a particular approach, so clarify scheduling constraints before coding.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
limit async workers run the same loop: take the next index, await the mapper, store the result at that index. The shared next++ is safe because JavaScript runs one piece of code at a time, so two workers can't take the same index. The timing check shows it's a sliding window: with durations 50, 10, 10, 10 and a limit of 2, items start at 0, 0, 10 and 20 ms and everything is done at 50 ms. The last two checks show its gaps: after a failure the surviving worker keeps starting items, and a limit of 0 does nothing without complaint.
// Start `limit` workers. Each one takes the next index until none are left.// Results go in by index, so the output keeps the input order.async function mapLimit(items, limit, fn) {const results = new Array(items.length);let next = 0;async function worker() {while (next < items.length) {const i = next++;results[i] = await fn(items[i], i);}}await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));return results;}
passes 9 checks run on every build, against the native method where there is one
- results keep the input order, whatever finishes first
- never more than `limit` running at once
- a freed slot is reused at once (sliding window, not chunks)
- fn receives the item and its index
- empty list and a limit above the length
- rejects with the first failure
- a limit of Infinity runs everything at once
- the weakness: after a failure the other worker keeps starting items
- the weakness: limit 0 silently maps nothing
The same schedule as an explicit pool: launch fills free slots, and each finished call frees its slot and calls launch again. A failed flag stops new items from starting once one has rejected, so a failure doesn't trigger more requests whose results nobody will read. Calls already running can't be stopped from here; that needs a signal (next stage). A synchronous throw in the mapper becomes a rejection, and a limit that isn't a positive integer rejects with a RangeError.
// Same sliding window, written as a pool: whenever a slot frees up, start the next item.// After a failure nothing new starts, and a bad limit is an error instead of a silent no-op.function mapLimit(items, limit, fn) {return new Promise((resolve, reject) => {if (!Number.isInteger(limit) || limit < 1) throw new RangeError('limit must be a positive integer');const results = new Array(items.length);let next = 0;let active = 0;let failed = false;if (items.length === 0) return resolve(results);const launch = () => {while (!failed && active < limit && next < items.length) {const i = next++;active++;// The extra then() turns a synchronous throw inside fn into a rejection.Promise.resolve().then(() => fn(items[i], i)).then((value) => {results[i] = value;active--;if (next === items.length && active === 0) resolve(results);else launch();},(error) => {failed = true;reject(error);},);}};launch();});}
passes 9 checks run on every build, against the native method where there is one
- results keep the input order, whatever finishes first
- never more than `limit` running at once
- a freed slot is reused at once (sliding window, not chunks)
- fn receives the item and its index
- empty list and a limit above the length
- rejects with the first failure
- after a failure nothing new starts
- a synchronous throw in fn is a rejection, on any item
- a limit that isn't a positive integer is rejected
settle: true records { status, value | reason } for every item, like Promise.allSettled, and never rejects: use it when one bad item shouldn't lose the rest. signal cancels the run: nothing new starts, the promise rejects with the signal's reason, and the mapper gets the signal so it can pass it to fetch and stop work in flight. mapInChunks is the other scheduling, kept for comparison: the same durations start at 0, 0, 50 and 50 ms and finish at 60 ms instead of 50.
// Options: `settle` collects every outcome instead of stopping at the first failure, and// `signal` cancels: nothing new starts, and fn receives the signal to stop its own work.function mapLimit(items, limit, fn, { signal, settle = false } = {}) {return new Promise((resolve, reject) => {if (!Number.isInteger(limit) || limit < 1) throw new RangeError('limit must be a positive integer');signal?.throwIfAborted();const results = new Array(items.length);let next = 0;let active = 0;let stopped = false;if (items.length === 0) return resolve(results);const fail = (error) => {stopped = true;reject(error);};signal?.addEventListener('abort', () => fail(signal.reason), { once: true });const done = (i, result) => {results[i] = result;active--;if (next === items.length && active === 0) resolve(results);else launch();};const launch = () => {while (!stopped && active < limit && next < items.length) {const i = next++;active++;Promise.resolve().then(() => fn(items[i], i, signal)).then((value) => done(i, settle ? { status: 'fulfilled', value } : value),(reason) => (settle ? done(i, { status: 'rejected', reason }) : fail(reason)),);}};launch();});}// The other scheduling an interviewer may mean: fixed chunks. Shorter, but one slow item holds// up its whole chunk, so it is slower than the sliding window above.async function mapInChunks(items, size, fn) {const results = [];for (let i = 0; i < items.length; i += size) {const chunk = items.slice(i, i + size);results.push(...(await Promise.all(chunk.map((item, k) => fn(item, i + k)))));}return results;}
passes 13 checks run on every build, against the native method where there is one
- results keep the input order, whatever finishes first
- never more than `limit` running at once
- a freed slot is reused at once (sliding window, not chunks)
- fn receives the item and its index
- empty list and a limit above the length
- rejects with the first failure
- after a failure nothing new starts
- settle: every outcome, in order, and it never rejects
- abort: rejects with the signal's reason and starts nothing more
- an already aborted signal starts nothing
- fn receives the signal
- a limit that isn't a positive integer is rejected
- mapInChunks: same results, but a slow item holds up its chunk
Bulk requests without flooding the server
Uploading 500 files or fetching 500 records with a plain Promise.all starts every request at once. A limit keeps a steady few in flight, which is kinder to the server and to the browser's own connection queue.
p-map and async.mapLimit
p-map takes a concurrency option and a stopOnError switch; the async library's mapLimit is the callback-era version of the same sliding window.
Cancelling with AbortSignal
fetch accepts a signal, so passing the run's signal to the mapper stops requests that are already in flight, not only the ones that haven't started.
awaitinside aforloop: that's a limit of 1.Promise.all(items.map(fn)): every call has already started, so there's no limit at all.Pushing results as they finish, which returns them in completion order instead of input order.
Chunking when a sliding window was asked for (or the reverse) without checking first.
Letting queued items keep starting after one has failed.
Not handling a limit of 0, a limit above the length, or an empty list.
Why is the shared counter safe without a lock?
JavaScript runs each piece of synchronous code to completion on one thread. const i = next++ can't be interrupted, so no two workers ever read the same value. Workers only interleave at await.
What's the total time compared with chunks?
With a sliding window a slot is never idle while items remain, so the run is as short as the limit allows. Chunks wait for the slowest item of each chunk before starting anything else, so idle slots add up.
How would you add retries?
Wrap the mapper: a function that calls fn, and on failure waits and tries again up to N times. The pool doesn't change, and the limit still counts a retrying item as one running slot.
Can you stop calls that are already running?
Only if the work itself supports it. Pass an AbortSignal to the mapper and on to fetch; a promise on its own can't be cancelled.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
- developer.mozilla.org/en-US/docs/Web/API/AbortSignal
- developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted
- github.com/sindresorhus/p-map
- caolan.github.io/async/v3/docs.html#mapLimit