chunk(array, size) steps through the array size at a time and slices; a size below 1 gives []. mapAsync is Promise.all(items.map(fn)): every call starts at once and the results keep their order. mapWithChunksAsync runs one chunk at a time, waiting for the whole chunk (await Promise.all(chunk.map(fn))) before the next, which caps how many requests are in flight. The better answer to that follow-up is a sliding window: start a new call the moment any finishes, so one slow item doesn't hold up the rest of its chunk.
Lodash's chunk()/map() with follow up of mapAsync(Promise.all) then mapWithChunksAsync
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.
chunk is a loop that steps by size and slices, so the last group holds the remainder. Math.floor keeps fractional sizes sane, and !(n >= 1) catches 0, negatives and NaN at once. mapAsync creates every promise before awaiting any, so all calls run together and Promise.all puts the results back in input order.
// Split an array into groups of `size`; the last group holds what is left.function chunk(array, size = 1) {const n = Math.floor(size);if (!(n >= 1)) return []; // 0, negatives and NaN give no groupsconst out = [];for (let i = 0; i < array.length; i += n) out.push(array.slice(i, i + n));return out;}// Run an async function on every item at once; results keep the input order.function mapAsync(items, fn) {return Promise.all(items.map((item, i) => fn(item, i)));}
passes 4 checks run on every build, against the native method where there is one
- splits into groups, the last one shorter
- size defaults to 1; 0, negative and NaN give []
- an empty array gives []
- mapAsync starts everything at once and keeps order
Awaiting Promise.all on each chunk inside a for loop runs the chunks in sequence and the items of a chunk in parallel. That caps the load on a server at size requests. Pass the item's original index, not its index within the chunk, and let a rejection end the loop so later chunks never start.
function chunk(array, size = 1) {const n = Math.floor(size);if (!(n >= 1)) return [];const out = [];for (let i = 0; i < array.length; i += n) out.push(array.slice(i, i + n));return out;}// One chunk at a time; the items inside a chunk run in parallel.async function mapWithChunksAsync(items, fn, size) {const results = [];let offset = 0;for (const group of chunk(items, size)) {const base = offset;// Wait for the whole chunk before starting the next one.const values = await Promise.all(group.map((item, j) => fn(item, base + j)));results.push(...values);offset += group.length;}return results;}
passes 3 checks run on every build, against the native method where there is one
- chunks run one after another, items inside in parallel
- passes the original index
- a failure stops the remaining chunks
Chunks wait for their slowest item: with durations 30, 10, 20, 10, 5 and size 2, chunks finish at 55 ms; a window of 2 that refills as soon as a slot frees finishes at 40 ms. The window keeps a count of active calls and starts the next item whenever one settles. An AbortSignal lets the caller give up: the promise rejects with signal.reason, no new calls start, and the signal is passed to each call so a fetch inside can stop too.
// A sliding window: at most `limit` calls in flight, and a new one starts the moment any finishes,// instead of waiting for the slowest item of a chunk. Stops early on failure or on abort.function mapAsyncLimit(items, fn, limit, { signal } = {}) {return new Promise((resolve, reject) => {const results = new Array(items.length);let next = 0;let active = 0;let finished = false;const fail = (err) => {if (finished) return;finished = true;reject(err);};if (signal?.aborted) return fail(signal.reason);signal?.addEventListener('abort', () => fail(signal.reason), { once: true });const launch = () => {if (finished) return;if (next === items.length && active === 0) {finished = true;resolve(results);return;}while (!finished && active < limit && next < items.length) {const i = next++;active++;Promise.resolve().then(() => fn(items[i], i, { signal })).then((value) => {results[i] = value;active--;launch();}, fail);}};launch();});}
passes 5 checks run on every build, against the native method where there is one
- starts the next item as soon as any slot frees
- finishes sooner than chunks on uneven work
- rejects on the first failure and starts nothing new
- abort rejects with the signal's reason and stops new starts
- an already aborted signal rejects at once; empty input resolves to []
Bulk API calls without tripping rate limits
Syncing 2,000 records one request each: all at once hits the API's rate limit, one by one takes minutes. A window of 5 to 10 in flight is the usual middle ground; libraries such as p-map take a concurrency option for exactly this.
Batch endpoints
Many APIs accept a list per request with a maximum size (for example 100 IDs). chunk(ids, 100) turns 1,000 IDs into 10 requests, which can then run through the same window.
Stopping work when the user leaves
Passing one AbortSignal through every call means navigating away cancels both the queue and the requests already in flight (fetch(url, { signal })).
Using
array.length / sizein the loop condition with fractional sizes, and getting a hole or an infinite loop.awaitinsideitems.forEach(async ...):forEachdoesn't wait, so the function returns before anything finishes.Passing each chunk's local index to
fninstead of the original index.Calling
fnfor every item up front and then 'chunking' the promises: they have all started already.Not stopping new work after a failure, so a broken endpoint gets hammered with the rest of the queue.
Why is a sliding window faster than chunks?
Chunks idle while waiting for each chunk's slowest item; the window keeps every slot busy. Total time drops from the sum of each chunk's slowest item to roughly the total work divided by the limit.
How would you retry failed items?
Wrap fn in a retry with backoff (for (let attempt = 0; attempt < 3; attempt++) try { return await fn(x) } catch { await sleep(2 ** attempt * 100) }) and only reject the whole map when an item fails every attempt.
How do you keep results in order when calls finish out of order?
Write each result into results[i] by its original index rather than pushing it when it arrives.
- lodash.com/docs/4.17.15#chunk
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
- developer.mozilla.org/en-US/docs/Web/API/AbortSignal
- developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach