Parallel Limit
HardPromises & Async30 min5 tests
Implement a parallelLimit(tasks, limit) function that runs an array of async task functions with a maximum concurrency of limit.
Requirements
tasksis an array of functions, each returning aPromise<T>.- At most
limittasks run simultaneously. - Return a
Promise<T[]>that resolves with results in the original order. - If any task rejects, the returned promise rejects immediately.
Example
const delay = (ms, val) => () => new Promise(r => setTimeout(() => r(val), ms));
const results = await parallelLimit([
delay(30, 'a'), delay(10, 'b'), delay(20, 'c')
], 2);
// results === ['a', 'b', 'c']Hints (5)
- Use a queue/index pointer to track which task to start next.
- Keep a counter of currently running tasks; only start a new one when running < limit.
- Store each result at its original index so order is preserved.
- When a task finishes, decrement the running counter and try to start the next task.
- Track total completed tasks and resolve when all are done.
Topics
- Promises & Async
Asked at
Google · Meta · Uber · Stripe
