Facebook Pixel

PromiseAll With Concurrency Limit

JavaScript
medium
25 mins

Implement a function that works like Promise.all() but with a concurrency limit. The function should take an array of functions that return promises and execute no more than a specified number of promises at any given time. Once a promise resolves, a new promise should be executed if there are any remaining.

Example Inputs & Outputs

// Example 1: // Input: const functions1 = [ () => new Promise(resolve => setTimeout(() => resolve(1), 100)), () => new Promise(resolve => setTimeout(() => resolve(2), 50)), () => new Promise(resolve => setTimeout(() => resolve(3), 150)) ]; promiseAllWithConcurrencyLimit(functions1, 2) // Expected Output: [1, 2, 3] // Example 2: // Input: const functions2 = [ () => new Promise(resolve => setTimeout(() => resolve(1), 200)), () => new Promise((_, reject) => setTimeout(() => reject("Error"), 100)), () => new Promise(resolve => setTimeout(() => resolve(3), 50)) ]; promiseAllWithConcurrencyLimit(functions2, 1) // Expected Output: Promise rejected with "Error"

Constraints & Edge Cases

  • The limit parameter will be a positive integer.
  • The order of results should match the order of input functions, regardless of completion time.
  • If any promise rejects, the returned promise should reject with that error.
  • If the functions array is empty, return an empty array.
  • Handle edge cases where limit is greater than the number of functions.

Companies:

netflix
uber
paytm

Solve Similar questions šŸ”„