Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 22

Asynchronous Task Queue

This lesson is built with resources from stackoverflow.com and davidgomes.com.

Hello! Welcome back to our series on advanced asynchronous patterns.

In our last lesson, we mastered the promise pool, a powerful pattern for executing a large number of asynchronous tasks with a controlled level of concurrency. We focused on maximizing throughput by running tasks in parallel up to a specified limit.

Today, we're going to tackle the opposite but equally important challenge: what if you need to ensure tasks run one after the other, in a strict sequence? For instance, when interacting with an API that requires ordered operations, writing to a log, or managing state where the outcome of one task is the prerequisite for the next.

The learning outcome for this lesson is to create an async queue to manage the sequential execution of asynchronous tasks. This pattern ensures that task B doesn't start until task A has fully completed, bringing order and predictability to your asynchronous workflows.

1. The Need for Sequential Execution

Imagine you are working with a server that is a bit fragile. As described in the article "Async Queue – One of My Favorite Programming Interviews...", if this server receives multiple requests at once, it breaks down. Your goal on the client-side is to ensure that you only ever have one request "in-flight" at any given time.

This creates a classic producer-consumer problem. Your application (the producer) generates tasks (e.g., API calls) at an unpredictable rate. A queueing mechanism must hold these tasks and feed them to a consumer one by one, waiting for each to finish before starting the next.

Asynchronous Queue System Diagram
This diagram illustrates the general architecture. A 'Producer' adds tasks to an 'Async Queue'. A 'Consumer' then pulls tasks from the queue and processes them one at a time. This model prevents the consumer from being overwhelmed.

A naive approach might involve checking a flag before sending a request, but this can fail in the tiny window of time between checking the flag and the asynchronous operation actually starting. Let's explore robust solutions.


2. The Promise Chain Pattern

One of the most elegant ways to enforce sequential execution in JavaScript leverages the nature of promises themselves. A promise chain, created with .then(), is inherently sequential. Each .then() callback only executes after the preceding promise in the chain has resolved. We can use this to build a simple but effective async queue.

JS async / await tasks queue

The Stack Overflow answer 'JS async / await tasks queue' provides a wonderfully concise solution using this promise-chaining technique. It's a great example of using language features to create powerful patterns.

In the provided resource, find the answer by user 'Nina Scholz' that begins with 'I would think there is a simple solution like follows.' Study the AsyncQueue class implementation and the example usage.

Let's break down how this works.

class AsyncQueue {
  constructor() {
    // The 'head' of our queue is a promise that is already resolved.
    this.promise = Promise.resolve();
  }

  // The task is a function that returns a promise.
  push(task) {
    // We chain the new task to the end of the current promise chain.
    // The new task will only execute after the previous one finishes.
    // We then update `this.promise` to point to the new end of the chain.
    this.promise = this.promise.then(task);
    return this.promise; // Optional: return the promise for this task
  }
}

// --- Example Usage ---
const q = new AsyncQueue();

const createTask = (id, delay) => async () => {
  console.log(`[${new Date().toLocaleTimeString()}] Task ${id} starting (will take ${delay}ms)`);
  await new Promise(resolve => setTimeout(resolve, delay));
  console.log(`[${new Date().toLocaleTimeString()}] Task ${id} finished.`);
};

q.push(createTask(1, 1000));
q.push(createTask(2, 500));
q.push(createTask(3, 200));

/*
Expected Output:
[HH:MM:SS] Task 1 starting (will take 1000ms)
[HH:MM:SS] Task 1 finished.
[HH:MM:SS] Task 2 starting (will take 500ms)
[HH:MM:SS] Task 2 finished.
[HH:MM:SS] Task 3 starting (will take 200ms)
[HH:MM:SS] Task 3 finished.
*/

The core of this pattern is the single line: this.promise = this.promise.then(task). Every time you push a new task, you are telling it to wait until the entire existing chain of tasks has completed. The this.promise property always points to the last promise in the sequence, acting as the tail of the queue.


3. The State-Based Worker Pattern

Another common approach is more explicit, managing the queue with an array and a state flag. This pattern is often called a "worker" or "drain" queue. It might feel more familiar if you've implemented queue data structures before.

The logic is as follows:

  1. Have a queue (an array) to store tasks.
  2. Use a boolean flag, let's call it isProcessing, to track if a task is currently running.
  3. When a task is added: push it to the queue. If nothing is currently processing (!isProcessing), start a "worker" process.
  4. The worker process:
    a. Sets isProcessing = true.
    b. Takes the first item from the queue.
    c. Executes it.
    d. When the task is done, the worker calls itself to process the next item.
    e. If the queue becomes empty, it sets isProcessing = false and goes dormant.

Async Queue – One of My Favorite Programming Interviews ...

The article 'Async Queue – One of My Favorite Programming Interviews ...' provides an excellent walkthrough of this pattern, including showing a common bug in a naive implementation before presenting the correct one.

Read the sections presenting the 'naive, faulty implementation' and then the corrected version that uses an isProcessing flag. This comparison is very instructive.

The key insight from the article is the need for the isProcessing flag to prevent a race condition where multiple sendOnce calls could start processing before the first one has marked the system as "busy."


4. A More Robust, Class-Based Queue

While the promise-chain method is elegant, it doesn't easily allow you to get the result of a specific task you've enqueued. The push method returns the promise for the end of the queue, not for the task you just added.

Let's analyze a more advanced implementation that solves this. It combines the worker pattern with a clever use of promises to give you a handle for each individual task's result.

JS async / await tasks queue

Let's return to the Stack Overflow thread and examine the most upvoted answer. It presents a full-featured AutoQueue class that provides a robust solution.

Carefully study the code for the Queue and AutoQueue classes. We will dissect the enqueue and dequeue methods next.

Let's break down the AutoQueue class.

enqueue(action) Method:

enqueue(action) {
  return new Promise((resolve, reject) => {
    super.enqueue({ action, resolve, reject });
    this.dequeue();
  });
}
  • Returns a new Promise: This is the key. For every task you add, you get a unique promise back that will settle (resolve or reject) when your specific task is done.
  • Wraps the task: It doesn't just push the action (your async function) onto the queue. It pushes an object containing the action along with the resolve and reject functions of the new promise. This gives the dequeue method the power to settle the promise later.
  • Triggers the worker: It calls this.dequeue(), which acts as our worker, to start processing if the queue isn't already running.

dequeue() Method:

async dequeue() {
  if (this._pendingPromise) return false; // The worker is already running

  let item = super.dequeue();
  if (!item) return false; // The queue is empty

  try {
    this._pendingPromise = true; // Set the 'isProcessing' flag

    let payload = await item.action(this); // Execute the task

    this._pendingPromise = false; // Unset the flag
    item.resolve(payload); // Resolve the promise for THIS task
  } catch (e) {
    this._pendingPromise = false; // Unset the flag on error
    item.reject(e); // Reject the promise for THIS task
  } finally {
    this.dequeue(); // Check for the next item in the queue
  }
}
  • _pendingPromise Flag: This is the equivalent of our isProcessing flag. It prevents multiple dequeue calls from running in parallel.
  • try...catch...finally: This robustly handles both successful and failed tasks.
  • item.resolve(payload) / item.reject(e): This is where the magic happens. After the action is awaited, the dequeue method uses the stored resolve or reject function to settle the promise that enqueue returned.
  • finally { this.dequeue() }: This is the "self-sustaining" part. After a task is complete (regardless of success or failure), it immediately attempts to start the next one. This ensures the queue is drained continuously until it's empty.
Test your understanding!

In the AutoQueue's dequeue method, what is the purpose of the _pendingPromise flag? What would happen if you removed all lines related to _pendingPromise?

Show answer

The _pendingPromise flag acts as a lock or a mutex. It ensures that only one task is being processed from the queue at any given time.

If you removed it, the following would happen:

  1. The first call to enqueue would trigger dequeue. dequeue would await item.action().
  2. While the first task is awaiting, a second call to enqueue would trigger dequeue again.
  3. Since there's no lock, this second dequeue call would pull the second item from the queue and start executing it in parallel with the first one.
  4. The fundamental purpose of the queue—sequential execution—would be completely broken. It would behave more like a simple concurrent loop.

Conclusion

You now have a powerful new tool in your asynchronous toolkit. Where promise pools help you manage concurrency, async queues help you enforce order. Understanding both patterns allows you to precisely control the flow and execution of asynchronous operations in complex applications.

Key Takeaways:

  • An async queue ensures that asynchronous tasks are executed one at a time, in the order they were added (First-In, First-Out).
  • It solves problems where sequential execution is a requirement, such as with stateful APIs or ordered data processing.
  • A simple and elegant implementation can be achieved using a promise chain, where each new task is appended to the .then() of the previous one.
  • A more explicit implementation uses a state-based worker pattern with an array as the queue and a flag (e.g., isProcessing) to prevent concurrent execution.
  • For a more robust solution, a class-based approach can provide a promise for each individual enqueued task, allowing you to handle its specific result.

Next Up

We have explored controlling how many tasks run (pools) and in what order they run (queues). In the next lesson, we will look at another crucial aspect of control: timing. We will learn how to implement a debounce function, a technique for rate-limiting asynchronous operations by ensuring a function is not called again until a certain amount of time has passed without it being called. This is essential for handling high-frequency events like search input or window resizing.