I am online
← Back to Articles

Cancel A Request In JavaScript

JavaScriptApril 15, 2024

Introduction

Aborting requests built with Promises was difficult until JavaScript introduced AbortController and AbortSignal.

These tools let developers cancel one or more requests using a signal.

The AbortController

Create an instance of the AbortController

const controller = new AbortController();
const { signal } = controller;

To cancel a request, use the controller's only available method - abort:

controller.abort();

Aborting a request notifies the signal:

signal.addEventListener("abort", () => {
  // Prints "true"
  console.log(signal.aborted);
});

Thanks for reading, enjoy, and happy coding!