FrontendInterviews.dev

Loading problem…

21. Promise Limit - K Parallel Tasks

Medium•

Implement promiseLimit(tasks, k) to control the number of concurrently executing asynchronous tasks.

You are given an array of functions, where each function returns a Promise. Execute these tasks such that at most k promises are running at any given time.

Requirements

Concurrency Control

  • At most k tasks should run in parallel.
  • When a running task settles (resolves or rejects), the next pending task should start.

Lazy Execution

  • Tasks must not be executed until a concurrency slot is available.

Order Preservation

  • The final result array must preserve the order of the input tasks, regardless of completion timing.

Rejection Handling

  • If any task rejects, immediately reject the returned promise with the same error.
  • No further tasks should be started after a rejection (similar to Promise.all).

Example

const tasks = [
  () => new Promise(resolve => setTimeout(() => resolve(1), 100)),
  () => new Promise(resolve => setTimeout(() => resolve(2), 200)),
  () => new Promise(resolve => setTimeout(() => resolve(3), 300)),
  () => new Promise(resolve => setTimeout(() => resolve(4), 400)),
];

promiseLimit(tasks, 2).then(results => {
  console.log(results); // [1, 2, 3, 4]
});

Constraints

  • 0 <= tasks.length <= 100
  • 1 <= k <= 100
  • All tasks return promises
  • Results must be in same order as input
  • If any promise rejects, the result should reject
  • At most k promises should run concurrently
Accepted28/39|Acceptance Rate71.8%