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

  • tasks is an array of functions, each returning a Promise<T>.
  • At most limit tasks 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)
  1. Use a queue/index pointer to track which task to start next.
  2. Keep a counter of currently running tasks; only start a new one when running < limit.
  3. Store each result at its original index so order is preserved.
  4. When a task finishes, decrement the running counter and try to start the next task.
  5. Track total completed tasks and resolve when all are done.

Topics

  • Promises & Async

Asked at

Google · Meta · Uber · Stripe

Join Us
blur