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.
  • concurrency limit (1 = strictly sequential).
  • pause() / start().
  • onIdle() → resolves when nothing is running or waiting.
  • size (waiting) and pending (running).
  • Cancellation: a task whose AbortSignal aborts before it starts is removed and rejected.

Implementation outline

  1. Keep a waiting list (sorted by priority, stable for equal priorities) and a running counter.
  2. add pushes an entry containing the task, its resolve/reject, priority and signal, then calls #next().
  3. #next() starts tasks while running < concurrency and not paused. Each task:
    • increments running;
    • runs Promise.resolve().then(task) so synchronous throws become rejections;
    • settles the caller's promise;
    • in finally, decrements running and calls #next() again.
  4. When running === 0 and the list is empty, resolve all onIdle waiters.

Design notes

  • One failing task must not stop the queue.
  • Starting tasks from finally keeps the pipeline full.
  • For large backlogs, a binary heap makes priority insertion O(log n) instead of O(n).
  • Libraries like p-queue provide this, plus rate limiting (interval caps).

Code example

js
1class AsyncQueue {
2 #waiting = [];
3 #running = 0;
4 #paused = false;
5 #idleWaiters = [];
6
7 constructor({ concurrency = 1 } = {}) {
8 this.concurrency = concurrency;
9 }
10
11 get size() { return this.#waiting.length; }
12 get pending() { return this.#running; }
13
14 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 insert
19 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 }
31
32 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 }
37
38 #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}
56
57const 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};
68
69queue.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();
78
79console.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.

Open in study app