FrontendPro

47Implement promisePool() using worker loops

mediumAbout 35 minutesCodingpromisesconcurrencyasync

Problem

Implement promisePool(tasks, concurrency, { settle = false } = {}). tasks is an array of functions that each return a promise. The pool runs at most concurrency of them at a time and resolves with their results in input order.

Use the worker loop pattern: start concurrency async loops that each keep taking the next task until none are left.

  • With settle: false (default), reject on the first failure and start no new tasks.
  • With settle: true, never reject; resolve with { status: "fulfilled", value } or { status: "rejected", reason } per task, like Promise.allSettled.
const tasks = files.map((file) => () => upload(file)); // not started yet
const urls = await promisePool(tasks, 3);

Requirements

  • A task function is only called when a worker is free to run it.
  • At most concurrency tasks run at once.
  • Results keep the input order.
  • concurrency below 1 is treated as 1.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Step-by-step

A promise starts its work when it is created. If you passed promises, every upload would already be running. Passing functions lets the pool decide when each one starts.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever