AniUI Academy

Run tasks with bounded concurrency

hardAsync & Promises+350 XPPractice

Firing every request at once exhausts the browser's connection pool and can get you rate-limited; running them one by one wastes minutes. The middle ground is a pool that keeps a fixed number in flight.

Implement pool(tasks, limit), where tasks is an array of zero-argument functions returning promises. Start the first limit tasks immediately; each time one fulfils, start the next task that has not run yet. Resolve with an array of the results in the original task order, not completion order. Never have more than limit tasks running at once. An empty array resolves with an empty array. If a task rejects, reject with that reason and do not start any task that has not already begun.

Arguments

tasksArray<() => Promise<T>>
Zero-argument functions returning promises.
limitnumber
Maximum number of tasks allowed to run concurrently.

Returns

Promise<Array<T>> — Resolves with results in original task order. Rejects with the first rejection and starts no further tasks.

Examples

const make = (n) => async () => {
  await new Promise((r) => setTimeout(r, 15));
  return n;
};
const results = await pool([make(1), make(2), make(3), make(4), make(5)], 2);
// results === [1, 2, 3, 4, 5] — at most 2 running at once, order preserved.

Bounded concurrency without losing input order.

What it has to do

  • Never run more than limit tasks at the same time.
  • Start a waiting task as soon as a running one finishes.
  • Resolve with results in the original task order.
  • Resolve with [] for an empty task list.
  • Reject on the first rejection and start no further tasks.

Notes

  • Keep a shared nextIndex cursor and have each worker's completion handler pull the next index — simpler than a chunk-based approach.
  • A rejection stops new tasks from starting but doesn't cancel ones already in flight; browser fetch needs an AbortController for actual cancellation.
Asked atGoogleUberNetflix

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +350 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.