FrontendInterviews.dev

Loading problem…

21. Promise Limit - K Parallel Tasks

Medium•
Acceptance: 84.21%
•
🔓3/3 Pro unlocks today

Implement a function that limits the number of concurrent promise executions. Given an array of promise-returning functions and a limit k, execute at most k promises in parallel.

You are given an array of functions that return promises, and a limit k. Your task is to implement a function that:

  • Executes at most k promises concurrently
  • When a promise completes, immediately start the next one
  • Returns a promise that resolves with an array of results in the same order as input
  • Handles promise rejections appropriately

Requirements

1. Basic Functionality

  • Accept array of promise-returning functions
  • Accept limit k (number of concurrent executions)
  • Execute at most k promises at a time
  • Start next promise when one completes
  • Return results in same order as input
  • Handle rejections (should reject if any promise rejects)

Example Usage

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)),
];

// Run at most 2 tasks in parallel
promiseLimit(tasks, 2).then(results => {
  console.log(results); // [1, 2, 3, 4] (in order)
});

Real-World Context

This problem models real concurrency control:

  • API rate limiting: Limit concurrent API requests
  • Resource management: Control database connection pool
  • File processing: Limit concurrent file operations
  • Network requests: Control concurrent network calls

Constraints

  • 1 <= tasks.length <= 100
  • 1 <= k <= tasks.length
  • 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