Cancel an API request in JavaScript

Explain a way to cancel the ongoing API request if it is not fulfilled.

JavaScript web API’s have a method called AbortController. This AbortController has a property called signal that allows us to create an AbortSignal that can be associated with the Fetch API which provides an option to abort the API request.

The signal is passed as a parameter to the fetch API.

To make this work we will create a constructor of the AbortController() and get its signal property. Pass this signal property as a parameter to the fetch API and invoke the abort method of the constructor whenever we want to cancel the API request.

When abort() is called, the fetch() promise rejects with an AbortError

In the below example, we have created two buttons, download and abort. On the download click, an API request will be made and on the abort click the request will be aborted.

HTML

<div>
  <button class="download">Download</button>
  <button class="abort">Abort</button>
</div>

JavaScript

// create abort controller
const controller = new AbortController();
const signal = controller.signal;

// get the buttons
const downloadBtn = document.querySelector(".download");
const abortBtn = document.querySelector(".abort");

// download event
downloadBtn.addEventListener("click", makeCall);

// abort event
abortBtn.addEventListener("click", () => {
  controller.abort();
  console.log("Download aborted");
});

// helper method to make api call
function makeCall() {
  fetch('https://jsonplaceholder.typicode.com/photos', { signal })
    .then((response) => {
      console.log("complete", response);
    })
    .catch((err) => {
      console.error(`error: ${err.message}`);
    });
};

Throttle on slow 2G in the developer tools and hit on the download button, later click on abort, the API call will terminate with the abort error.