Async task pool with a limit
Run thousands of async tasks, but no more than N at a time – as when downloading files or calling a rate-limited API. Promises, result order and stopping at the first error.
A migration script has to call an external API for 20,000 records. Promise.all(records.map(call)) starts everything at once and the API answers 429 or falls over. We need a pool – at most limit tasks in flight, with the next one starting as soon as a slot frees up. The task is about JavaScript/TypeScript (Node.js, browser) – promises and the event loop.
Task
runWithLimit(tasks, limit) – tasks is an array of functions (not promises!), each returning a promise or a plain value when called. The function returns a promise that:
- resolves to an array of results in task order (not completion order),
- starts tasks in array order and never has more than
limitin flight, - starts the next task immediately when one finishes (without waiting for a whole "batch"),
- on the first error (a rejected promise or an exception thrown by a task function) rejects with that error and starts no new tasks; running ones may finish, but their results are ignored,
- resolves to
[]for an empty array, - rejects with a
RangeErrorwhenlimitis not a positive integer.
Example
limit = 2, tasks take: A – 300 ms, B – 100 ms, C – 100 ms, D – 50 ms:
| Time [ms] | Event |
|---|---|
| 0 | A and B start |
| 100 | B ends → C starts |
| 200 | C ends → D starts |
| 250 | D ends |
| 300 | A ends → result [A, B, C, D] |
Constraints
- Up to 20,000 tasks,
1 ≤ limit ≤ 1,000.
Expected complexity
Pool overhead O(n) time and O(n) memory (for results); no sorting and no shift() in a loop.