How to cancel a request in JavaScript

As we all know, JavaScript implements asynchronous requests by relying on two APIs provided by the browser - XMLHttpRequest and Fetch. We usually use the Promise request library axios, which is based on XMLHttpRequest.
This article brings how XMLHttpRequest, Fetch and axios "cancel the request" respectively.
Don't gossip, just rush and it's over~

Cancel XMLHttpRequest request


When the request has been sent, you can use the XMLHttpRequest.abort() method to cancel the sending. The code example is as follows:
const xhr = new XMLHttpRequest();
xhr.open('GET', '', true);
xhr.send();
setTimeout(() => {
xhr.abort();
}, 1000);

Cancel the request, readyState will become XMLHttpRequest.UNSENT(0); the requested xhr.status will be set to 0;
Let's take a look at the comparison chart of normal and canceled requests in the Chrome DevTools Network:

Cancel a Fetch request


To cancel the Fetch request, you need to use the AbortController API. We can construct a controller instance: const controller = new AbortController() , controller It has a read-only property AbortController.signal, which can be passed as a parameter to fetch to associate the controller with the fetch request;
The code example is as follows:
const controller = new AbortController();
void (async function () {
const response = await fetch('', {
signal: controller.signal,
});
const data = await response.json();
})();

setTimeout(() => {
controller.abort();
}, 1000);

Browser console comparison chart:

We can actually pass in the "reason for canceling the request" parameter in controller.abort(), and then try...catch to capture

cancel aixos request


axios also supports AbortController
const controller = new AbortController();
const API_URL = '';
void (async function () {
const response = await axios.get(API_URL, {
signal: controller.signal,
});
const { data } = response;
})();
setTimeout(() => {
controller.abort();
}, 1000);

Console screenshot:

Error catch:

Note: The CancelToken method used by axios to cancel requests has been deprecated. For more information, please refer to the documentation axios-http.com/docs/cancel…;

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00