JavaScript · Promises · Senior · Live Coding
Implement or design a promise pool that runs at most N async tasks at a time.
Short Interview Answer
Keep a queue of task factories, start up to N, and start the next when one finishes; return results in input order if required.
Detailed Explanation
APIs often need bounded concurrency for rate limits and memory. Pattern: map items to async functions, maintain `active` count, dequeue when slots free. Preserve order with result index array. Decide error policy: fail fast (cancel remaining) vs collect errors. Use AbortSignal for cancellation. Libraries exist (p-limit, p-map), but interviews may ask for a sketch. Discuss fairness and starvation under mixed task durations.
Example
async function pool(items, worker, n = 4) {
const ret = new Array(items.length);
let i = 0;
async function run() {
while (i < items.length) {
const idx = i++;
ret[idx] = await worker(items[idx], idx);
}
}
await Promise.all(Array.from({ length: Math.min(n, items.length) }, run));
return ret;
}Interview Tip
Clarify ordered results vs completion order up front.
Common Mistake
Starting all promises then only awaiting slices — does not limit start concurrency.