JavaScriptHard
Implement an Async Queue
A production-grade async queue accepts tasks (functions returning promises), runs at most concurrency of them at a time, resolves each add() with that task's own result or error, and supports priorities, pausing, cancellation and an onIdle() promise.
API
add(task, { priority, signal })→ promise of the task's result.concurrencylimit (1 = strictly sequential).pause()/start().onIdle()→ resolves when nothing is running or waiting.size(waiting) andpending(running).- Cancellation: a task whose
AbortSignalaborts before it starts is removed and rejected.
Implementation outline
- Keep a waiting list (sorted by priority, stable for equal priorities) and a running counter.
addpushes an entry containing the task, itsresolve/reject, priority and signal, then calls#next().#next()starts tasks whilerunning < concurrencyand not paused. Each task:- increments
running; - runs
Promise.resolve().then(task)so synchronous throws become rejections; - settles the caller's promise;
- in
finally, decrementsrunningand calls#next()again.
- increments
- When
running === 0and the list is empty, resolve allonIdlewaiters.
Design notes
- One failing task must not stop the queue.
- Starting tasks from
finallykeeps the pipeline full. - For large backlogs, a binary heap makes priority insertion O(log n) instead of O(n).
- Libraries like
p-queueprovide this, plus rate limiting (interval caps).
Code example
js
1class AsyncQueue {2 #waiting = [];3 #running = 0;4 #paused = false;5 #idleWaiters = [];67 constructor({ concurrency = 1 } = {}) {8 this.concurrency = concurrency;9 }1011 get size() { return this.#waiting.length; }12 get pending() { return this.#running; }1314 add(task, { priority = 0, signal } = {}) {15 return new Promise((resolve, reject) => {16 if (signal?.aborted) return reject(signal.reason);17 const entry = { task, priority, resolve, reject, signal };18 const i = this.#waiting.findIndex((e) => e.priority < priority); // stable priority insert19 i === -1 ? this.#waiting.push(entry) : this.#waiting.splice(i, 0, entry);20 signal?.addEventListener("abort", () => {21 const idx = this.#waiting.indexOf(entry);22 if (idx !== -1) {23 this.#waiting.splice(idx, 1);24 reject(signal.reason);25 this.#checkIdle();26 }27 }, { once: true });28 this.#next();29 });30 }3132 pause() { this.#paused = true; }33 start() { this.#paused = false; this.#next(); }34 onIdle() {35 return this.#running === 0 && this.#waiting.length === 0 ? Promise.resolve() : new Promise((r) => this.#idleWaiters.push(r));36 }3738 #next() {39 while (!this.#paused && this.#running < this.concurrency && this.#waiting.length) {40 const { task, resolve, reject } = this.#waiting.shift();41 this.#running++;42 Promise.resolve()43 .then(task)44 .then(resolve, reject)45 .finally(() => {46 this.#running--;47 this.#next();48 this.#checkIdle();49 });50 }51 }52 #checkIdle() {53 if (this.#running === 0 && this.#waiting.length === 0) this.#idleWaiters.splice(0).forEach((r) => r());54 }55}5657const sleep = (ms) => new Promise((r) => setTimeout(r, ms));58const queue = new AsyncQueue({ concurrency: 2 });59const log = [];60let peak = 0;61const job = (name, ms, fail = false) => async () => {62 peak = Math.max(peak, queue.pending);63 await sleep(ms);64 if (fail) throw new Error(`${name} failed`);65 log.push(name);66 return name;67};6869queue.pause();70const a = queue.add(job("A", 30));71const b = queue.add(job("B (fails)", 10, true)).catch((e) => e.message);72const c = queue.add(job("C low", 5), { priority: -1 });73const d = queue.add(job("D urgent", 5), { priority: 10 });74const controller = new AbortController();75const e = queue.add(job("E cancelled", 5), { signal: controller.signal }).catch(() => "E was cancelled");76controller.abort();77queue.start();7879console.log(await Promise.all([a, b, c, d, e])); // ["A", "B (fails) failed", "C low", "D urgent", "E was cancelled"]80await queue.onIdle();81console.log(log, "peak concurrency:", peak); // ["D urgent", "C low", "A"] peak concurrency: 2 (D ran first: highest priority)
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.