What is the Async Queue?

An async queue is a structure that runs asynchronous tasks in a controlled way, either one at a time in order or with a limited number running at once, so you can avoid race conditions, respect rate limits and keep resource use predictable.

Why you need one

  • Ordering: saving edits must happen in the order the user made them; if two save requests race, the older one may finish last and overwrite the newer data.
  • Concurrency limits: uploading 500 files with Promise.all fires 500 requests at once, overwhelming the browser, the server or an API's rate limit.
  • Backpressure: produce work faster than it can be processed without running out of memory.

Two common shapes

  1. Serial queue (concurrency 1): chain each task onto the previous promise. Simple and guarantees order.
  2. Pool with concurrency N: keep at most N tasks running; when one finishes, start the next.

Features of a robust queue

  • Each add(task) returns a promise for that task's own result.
  • One failing task does not stop the rest (or optionally it does, if order matters).
  • Events or callbacks for idle/drained state.
  • Optional priorities, retries, pausing and cancellation (AbortSignal).

Libraries and built-ins

Libraries like p-limit and p-queue are widely used. In Node, streams handle backpressure natively. The full implementation is covered in "Implement an Async Queue".

Code example

js
1// Serial queue: each task starts only after the previous one finished
2function createSerialQueue() {
3 let tail = Promise.resolve();
4 return (task) => {
5 const run = tail.then(() => task());
6 tail = run.catch(() => {}); // keep the chain alive after failures
7 return run; // callers still see their own errors
8 };
9}
10
11const wait = (ms) => new Promise((r) => setTimeout(r, ms));
12const enqueue = createSerialQueue();
13const saved = [];
14
15// The first save is slow, but order is still preserved
16enqueue(async () => { await wait(30); saved.push("edit 1"); });
17enqueue(async () => { await wait(5); saved.push("edit 2"); });
18await enqueue(async () => { saved.push("edit 3"); });
19console.log(saved); // ["edit 1", "edit 2", "edit 3"]
20
21// Concurrency-limited pool: at most `limit` tasks at once
22function pLimit(limit) {
23 let active = 0;
24 const waiting = [];
25 const next = () => {
26 if (active >= limit || !waiting.length) return;
27 active++;
28 const { task, resolve, reject } = waiting.shift();
29 task().then(resolve, reject).finally(() => {
30 active--;
31 next();
32 });
33 };
34 return (task) => new Promise((resolve, reject) => {
35 waiting.push({ task, resolve, reject });
36 next();
37 });
38}
39
40const limit = pLimit(2);
41let running = 0, peak = 0;
42const job = (n) => limit(async () => {
43 peak = Math.max(peak, ++running);
44 await wait(10);
45 running--;
46 return n * 2;
47});
48console.log(await Promise.all([1, 2, 3, 4, 5].map(job)), "peak concurrency:", peak); // [2, 4, 6, 8, 10] peak concurrency: 2

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