Run tasks with bounded concurrency
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
limittasks 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
nextIndexcursor 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
fetchneeds anAbortControllerfor actual cancellation.
Stuck? The javascript course covers everything this challenge needs.
- 1.respects the concurrency limit and keeps order
- 2.keeps the pool full as tasks finish
- 3.handles a limit larger than the task count
- 4.resolves with an empty array for no tasks
- 5.rejects on failure and starts no further tasks
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.