Promise Pool

PromisesConcurrencyAsync

Given an array of functions that each return a promise, and a number n, run them all but never more than n at the same time.

As soon as one finishes, the next should start — do not wait for a whole batch to complete. Resolve once every function has finished.

Examples

Example 1
Input
promisePool([f1, f2, f3], 2)  // f1: 300ms, f2: 400ms, f3: 200ms
Output
resolves after ~500ms
Explanation
f1 and f2 start together. f1 finishes at 300ms, freeing a slot for f3, which finishes at 500ms. Batching would have taken 600ms.

Constraints

  • 1 <= functions.length <= 10
  • 1 <= n <= 10
  • Every function returns a promise

Notes

  • Fixed batches are the common wrong answer: they idle until the slowest member of each batch finishes.

Hints

Read the full write-up for Promise Pool
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it