Promise Worker Pool
HardPromises & Async30 min5 tests
Implement createPool(worker, concurrency) that creates a pool of reusable workers with limited concurrency.
Requirements
worker(task)is an async function that processes a task.submit(task)— submit a task to the pool. Returns a promise that resolves with the worker's result. If all workers are busy, the task waits in a queue.drain()— returns a promise that resolves when all submitted tasks have completed.- At most
concurrencytasks run simultaneously.
Example
const pool = createPool(async (n) => n * 2, 2);
const r1 = pool.submit(5); // starts immediately
const r2 = pool.submit(10); // starts immediately
const r3 = pool.submit(15); // queued, waits for a slot
await pool.drain();Hints (5)
- Track the number of currently running tasks and a queue for pending ones.
- submit() adds a task to the queue and tries to start processing.
- tryNext() starts tasks from the queue while running < concurrency.
- When a task finishes, decrement running and call tryNext again.
- drain() returns a promise that resolves when running === 0 and queue is empty.
Topics
- Promises & Async
Asked at
Google · Amazon · Uber · Cloudflare
