Skip to main content

Welcome to a Grasp lesson

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

Lesson 20

Cancelling Asynchronous Operations with AbortController

This lesson is built with resources from youtube.com, kettanaito.com and 1 more site.

Hello! Welcome to the next lesson in our module on Advanced Asynchronous Patterns.

In our previous lesson, we demystified the for await...of loop, understanding how it sequentially consumes data from asynchronous iterables. We also saw that break or return can terminate a loop from the inside, triggering cleanup logic. But this raises a crucial question: what if we need to stop a long-running async operation from the outside? Imagine a user clicking a "Cancel" button during a large file upload or navigating away from a page while data is being fetched.

Today, we will tackle this exact problem. Our learning outcome is to build a cancellable asynchronous operation using AbortController and AbortSignal. This is the modern, standard JavaScript API for providing explicit cancellation capabilities to any asynchronous task.

1. The Core Components: Controller and Signal

The AbortController API is elegantly simple and composed of two main parts:

  • AbortController: An object that lets you create a signal and, crucially, broadcast an "abort" message to any operations listening to that signal. Think of it as the remote control.
  • AbortSignal: An object that acts as the receiver. You pass this signal to an asynchronous function, allowing it to listen for the abort message from the controller.

The fundamental workflow is:

  1. Create an instance of AbortController.
  2. Get the signal property from the controller instance.
  3. Pass this signal to one or more asynchronous functions.
  4. Call controller.abort() whenever you want to cancel the operations.

The complete guide to the AbortController API

For a concise textual introduction to these concepts, let's turn to 'The complete guide to the AbortController API' on the LogRocket blog. It clearly defines the controller, the signal, and their properties.

Read the introductory section, up to the heading 'How to use AbortController in Node.js'. Focus on the roles of new AbortController(), the signal property, the abort() method, and the aborted and reason properties on the signal.

As the article highlights, any function that is listening to the signal will be notified when controller.abort() is called. This notification happens via an abort event.


2. The Classic Use Case: Cancelling fetch Requests

The most common and straightforward use of AbortController is with the fetch API, which has built-in support for it. This makes it the perfect starting point.

You simply pass the signal as an option to your fetch call. If controller.abort() is called while the request is in flight, fetch will reject its promise with a special AbortError.

The Power of AbortController in JavaScript

The video 'The Power of AbortController in JavaScript' by Software Developer Diaries provides a clear, step-by-step demonstration of this.

Watch from 00:57 to 05:52. The video will walk you through adding a signal to a fetch request, calling abort(), and then correctly catching and identifying the AbortError in a try...catch block. It also shows how to pass a custom reason for the abort.

This pattern is fundamental:

const controller = new AbortController();
const signal = controller.signal;

// Trigger the cancellation after 500ms
setTimeout(() => controller.abort('Request timed out'), 500);

(async () => {
  try {
    console.log('Fetching data...');
    const response = await fetch('https://api.example.com/slow-endpoint', { signal });
    const data = await response.json();
    console.log('Data received:', data);
  } catch (error) {
    if (error.name === 'AbortError') {
      // The `reason` comes from the argument to `abort()`
      console.error('Fetch aborted:', controller.signal.reason); 
    } else {
      console.error('An unexpected error occurred:', error);
    }
  }
})();

3. Building Your Own Cancellable Operation

The true power of AbortController is that it's a generic pattern, not something specific to fetch. You can make any asynchronous function cancellable by adopting the same protocol. This is the core of today's lesson.

To make a custom function abortable, you need to:

  1. Accept a signal object as an argument (usually in an options object).
  2. Inside your function, listen for the 'abort' event on the signal. When it fires, you must take action to stop the work and reject your promise.
  3. Check if the signal is already aborted (signal.aborted) before starting any work.
  4. Implement cleanup logic to remove the 'abort' event listener if the operation completes successfully, preventing memory leaks.

This diagrammatic code example beautifully illustrates the complete pattern.

JavaScript AbortController Example
This image illustrates the complete pattern for creating a custom abortable async function. A `controller` is created, its `signal` is passed to `doSomethingAsync`. Inside this function, a promise is created. An event listener on the `signal` rejects the promise if an `abort` event is heard. The operation is cancelled from the outside by calling `controller.abort()`.

Let's implement this. Imagine a function that simulates a complex, multi-step process.

function longRunningProcess(options = {}) {
  const { signal } = options;

  // 1. Immediately reject if the operation was already cancelled.
  if (signal?.aborted) {
    return Promise.reject(new DOMException('Operation already aborted', 'AbortError'));
  }

  return new Promise((resolve, reject) => {
    // 2. Define the abort logic.
    const abortHandler = () => {
      clearTimeout(step1Timeout);
      clearTimeout(step2Timeout);
      reject(new DOMException(`Process aborted: ${signal.reason}`, 'AbortError'));
    };
    
    // 3. Listen for the abort signal.
    signal?.addEventListener('abort', abortHandler, { once: true });
    
    console.log("Starting Step 1...");
    const step1Timeout = setTimeout(() => {
      console.log("Step 1 Complete.");

      console.log("Starting Step 2...");
      const step2Timeout = setTimeout(() => {
        console.log("Step 2 Complete. Process finished.");
        // 4. Clean up the listener on successful completion.
        signal?.removeEventListener('abort', abortHandler);
        resolve({ success: true });
      }, 2000);
    }, 2000);
  });
}

// --- How to use it ---
const controller = new AbortController();

setTimeout(() => controller.abort('User cancelled the process.'), 3000); // Aborts after 3s

longRunningProcess({ signal: controller.signal })
  .then(result => console.log('Final result:', result))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.error(err.message); // -> Process aborted: User cancelled...
    }
  });

// Expected output:
// Starting Step 1...
// Step 1 Complete.
// Starting Step 2...
// (controller.abort() is called here)
// Process aborted: User cancelled the process.

The use of { once: true } when adding the event listener is a common and effective way to handle cleanup, as it automatically removes the listener after it's invoked once. However, if the operation succeeds, you must manually remove the listener to prevent it from lingering.

Test your understanding!

Modify the longRunningProcess function. What happens if you remove the line signal?.removeEventListener('abort', abortHandler);? Does this cause a "memory leak"? Why or why not?

Show answer

Yes, this can cause a memory leak. If the longRunningProcess function is called many times with the same AbortController instance (which is uncommon but possible) and it succeeds each time, a new abortHandler would be added to the signal's event listener list with every call. These listeners would never be removed.

More importantly, even if a new controller is used each time, the abortHandler closure holds references to step1Timeout and step2Timeout. If the operation succeeds, the abortHandler listener remains attached to the signal. The signal, in turn, is held by the controller. If you keep a reference to the controller somewhere, the garbage collector cannot clean up the listener or the context it closed over. It's a best practice to always clean up listeners when an operation is complete.


4. Advanced Cancellation Scenarios

The AbortSignal class itself provides powerful static methods for more complex cancellation logic.

I Cannot Believe Abort Controller Can Do This

The video 'I Cannot Believe Abort Controller Can Do This' from Web Dev Simplified masterfully demonstrates these advanced techniques.

Watch from 07:15 to 09:01. This segment introduces AbortSignal.timeout() for time-based cancellation and AbortSignal.any() for combining multiple signals. Pay close attention to how any() allows you to separate internal cancellation logic (like a timeout) from external cancellation logic (like a user action).

Let's summarize these powerful tools:

  • AbortSignal.timeout(milliseconds): A fantastic shorthand that returns a signal that automatically aborts after a specified duration. This is perfect for implementing timeouts on any abortable API without writing setTimeout logic yourself.
    // This fetch request will automatically abort if it takes longer than 3 seconds.
    fetch('/data', { signal: AbortSignal.timeout(3000) });
    
  • AbortSignal.any([signal1, signal2, ...]): Creates a new signal that aborts as soon as any of the provided signals are aborted. This is invaluable for composing cancellation conditions. For example, you can combine a user-cancellable signal with an automatic timeout signal.
    const userController = new AbortController();
    const timeoutSignal = AbortSignal.timeout(5000);
    
    // This operation will be cancelled if the user clicks 'cancel' OR if it takes longer than 5s.
    someAbortableOperation({
      signal: AbortSignal.any([userController.signal, timeoutSignal])
    });
    
    This pattern is particularly useful when writing libraries, as it lets you have internal cancellation logic while also allowing the user of your library to provide their own cancellation signal.

5. Applying the Pattern to Other APIs

Now that you know how to build a custom abortable function, you can wrap any third-party library or long-running task to make it cancellable.

I Cannot Believe Abort Controller Can Do This

Let's return to the Web Dev Simplified video, which has an excellent real-world example of this. It shows how to wrap a database transaction from the Drizzle ORM to make it abortable.

Watch from 08:52 to 13:59. You have experience with SQL and databases, so this example of making a transaction cancellable will be very relevant. Focus on the structure of the abortableTransaction wrapper function. Notice how it uses new Promise and listens to the signal's 'abort' event to reject and roll back the transaction—this is the exact pattern we discussed.

This demonstrates that AbortController is not just an API, but a design pattern for cooperative cancellation in JavaScript. By adhering to this pattern, you can introduce predictable, standardized cancellation into complex asynchronous workflows.


Conclusion

In this lesson, you've learned how to move beyond simply consuming async operations to actively managing their lifecycle.

Key Takeaways:

  • AbortController and AbortSignal provide a standard, cooperative mechanism for cancelling asynchronous operations.
  • The pattern involves creating a controller, passing its signal to an async function, and calling controller.abort() to trigger cancellation.
  • While many built-in APIs like fetch and addEventListener support signals natively, the real power lies in making your own custom functions abortable.
  • Implementing a custom abortable operation involves accepting a signal, checking if it's already aborted, listening for the abort event to reject the promise, and cleaning up the listener upon completion.
  • Advanced tools like AbortSignal.timeout() and AbortSignal.any() allow for sophisticated cancellation logic like automatic timeouts and combined triggers.

Next Up

We've now covered how to manage single asynchronous streams and how to cancel them. But what about when we have a large number of asynchronous tasks to run? Firing them all off at once can overwhelm network connections or APIs. In our next lesson, we will address this by learning how to implement a promise pool to control concurrency, ensuring we can process many tasks efficiently without overloading our resources.