Promise Pool - Problem

Given an array of asynchronous functions functions and a pool limit n, return an asynchronous function promisePool. It should return a promise that resolves when all the input functions resolve.

Pool limit is defined as the maximum number promises that can be pending at once. promisePool should begin execution of as many functions as possible and continue executing new functions when old promises resolve.

promisePool should execute functions[i] then functions[i + 1] then functions[i + 2], etc. When the last promise resolves, promisePool should also resolve.

For example, if n = 1, promisePool will execute one function at a time in series. However, if n = 2, it first executes two functions. When either of the two functions resolve, a 3rd function should be executed (if available), and so on until there are no functions left to execute.

You can assume all functions never reject. It is acceptable for promisePool to return a promise that resolves any value.

Input & Output

Example 1 — Pool Limit 2
$ Input: functions = [() => new Promise(res => setTimeout(res, 300)), () => new Promise(res => setTimeout(res, 400)), () => new Promise(res => setTimeout(res, 200))], n = 2
Output: Promise that resolves after ~500ms
💡 Note: First 2 functions start immediately. Function 1 (300ms) and function 2 (400ms) run concurrently. After 300ms, function 1 completes and function 3 (200ms) starts. Total time: max(300, 400) + 200 = 500ms.
Example 2 — Pool Limit 1
$ Input: functions = [() => new Promise(res => setTimeout(res, 100)), () => new Promise(res => setTimeout(res, 200))], n = 1
Output: Promise that resolves after 300ms
💡 Note: With n=1, functions execute sequentially: first function (100ms), then second function (200ms). Total: 100 + 200 = 300ms.
Example 3 — Empty Array
$ Input: functions = [], n = 3
Output: Promise that resolves immediately
💡 Note: No functions to execute, so the pool resolves immediately.

Constraints

  • 0 ≤ functions.length ≤ 10
  • 1 ≤ n ≤ 10

Visualization

Tap to expand
Promise Pool: Managing Concurrent Async Functionsfunc[0]func[1]func[2]func[3]func[4]300ms400ms200ms100ms250msPromise Pool (n=2)Maximum 2 concurrent executionsStart next function when any completesRunningRunningResult: Promise resolves when all functions complete
Understanding the Visualization
1
Input
Array of async functions and pool limit n
2
Process
Execute max n functions concurrently
3
Output
Promise that resolves when all complete
Key Takeaway
🎯 Key Insight: Keep exactly n promises running concurrently by immediately starting new functions when others complete
Asked in
Meta 25 Google 20
12.0K Views
Medium Frequency
~25 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen