← JavaScript Coding

Promise Pool

hardpromisesconcurrencyasync
Asked at
Amazon
Cloudflare
Datadog
Google
Meta
Uber
Amazon, Cloudflare, Datadog, Google, Meta, Uber

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 limit tasks 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 limit is less than 1.

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.

Premium

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
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingEasy

City Fetcher API

JS CodingHard

promise.all( )

JS CodingHard

promise.allSettled( )

JS CodingHard

promise.any( )

JS CodingHard

promise.race( )

JS CodingEasy

promise.reject()

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Amazon interview
  • Cloudflare interview
  • Datadog interview
  • Google interview
  • Meta interview
  • Uber interview