Promise Pool
Problem statement
Implement promisePool(tasks, limit). It receives an array of task functions and a concurrency limit. Each task function returns a promise or value.
The pool should run at most limit tasks at the same time and resolve with results in the same order as the input tasks.
Requirements
- Start up to
limittasks immediately. - Start the next task as soon as one running task finishes.
- Resolve to an array of results in input order, not completion order.
- Reject immediately when any task rejects.
- Handle synchronous return values and synchronous thrown errors.
- Reject when
limitis less than1.
This pattern appears in frontend rounds because browsers often need bounded async work: image preloads, API fan-out, upload queues, and analytics flushing.
Requirements & constraints
- Do not use external libraries.
- Never run more than `limit` tasks at once.
- Result order must match input order.
How to approach Promise Pool
The strategy an interviewer expects you to reach for.
A promise pool caps concurrency — upload 100 files but only 4 at a time so you do not melt the browser or the API. Naive move Promise.all(tasks.map(t => t())). Everything starts immediately. Where it breaks Connection limits, memory spikes, and rate limits. You still need results in input order and fail-fast (or defined) error behavior. The fix Track nextIndex, running, and completed. launchNext starts workers while running < limit. On settle, write results[i], decrement running, and launch more. Resolve when completed === length. Remember: Pool = worker slots + ordered result slots, not Promise.all. Say this in the interview: I'd keep a concurrency counter, start the next task whenever a slot frees, write results by index, and reject as soon as any task fails if fail-fast is required.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.