Promise Pool With a Concurrency Limit

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
const wait = (ms) => () => new Promise((r) => setTimeout(r, ms));

const t0 = Date.now();
await promisePool([wait(200), wait(500), wait(100), wait(250)], 2);
Date.now() - t0;
Output
~550
Explanation
The 200ms and 500ms tasks start together. The 200ms one frees its slot first, so the 100ms task runs from 200ms to 300ms, and the 250ms task then runs until 550ms. Fixed batches of two would have taken 500 + 250 = 750ms.

Constraints

  • The list may be empty, in which case the pool resolves straight away
  • n is at least 1 and may be larger than the number of functions
  • Each function starts its work only when the pool calls it, and 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 With a Concurrency Limit
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it