#Promises#Concurrency

Promise Pool

Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.

By Pratik RaiMedium

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

Input:

JSfile.javascript
1promisePool([f1, f2, f3], 2) // f1: 300ms, f2: 400ms, f3: 200ms

Output:

resolves after ~500ms

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.

Goal: Run every task with at most n in flight, starting the next the moment a slot frees.

Source

Frequently asked questions

What is a promise pool in JavaScript?
A promise pool runs a list of asynchronous tasks while limiting how many are in flight at any moment. `Promise.all` starts everything at once; a pool starts `n`, and begins the next task only as a running one finishes.
Why not just split the tasks into batches?
Because a batch cannot start until the slowest member of the previous batch finishes, so quick tasks sit idle waiting on a slow neighbour. Starting `n` workers that each pull the next unclaimed task keeps every slot busy and finishes measurably sooner.
Is a shared counter safe without locking?
Yes. JavaScript runs your code on a single thread, so `next += 1` cannot be interrupted halfway by another worker. This is one of the few places where the single-threaded model makes a concurrency problem simpler rather than harder.
Where would you use this in a real frontend?
Uploading a set of files, prefetching images, or hydrating a list where each row needs its own request. Browsers cap connections per host anyway, so firing fifty requests at once mostly builds a queue you cannot see and cannot prioritise.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Promise Time Limit

Wrap an async function so it gives up after a deadline — the building block behind every request timeout.

JavaScript · ES6Pratik Rai ·

JavaScript

Promisify a Callback Function

Convert a Node-style (error, value) callback API into one that returns a promise.

JavaScript · ES6Pratik Rai ·

JavaScript

Resolve Promises Sequentially

Run promises one after another and collect the results in order — built with .then chaining, no async/await.

JavaScript · ES6Pratik Rai ·