Polski

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.

medium · typescript · javascript · 20 XP

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 limit in 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 RangeError when limit is not a positive integer.

Example

limit = 2, tasks take: A – 300 ms, B – 100 ms, C – 100 ms, D – 50 ms:

Time [ms]Event
0A and B start
100B ends → C starts
200C ends → D starts
250D ends
300A 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.