Aborting a fetch Request, by GANAPATI V S

In today’s browsers, there are two main ways to send a request: XMLHttpRequest and FETCH. The XMLHttpRequest interface has been around in browsers for a long time, and FETCH is a feature introduced in ES2015.

XMLHttpRequest can be abortable midway through a request. Here’s an example:

let xhr = new XMLHttpRequest();
xhr.method = 'GET';
xhr.url = 'https://slowmo.glitch.me/5000';
xhr.open(method, url, true);
xhr.send();

// Abort the request at a later stage
abortButton.addEventListener('click'.function() {
  xhr.abort();
});
Copy the code

Fetch did not support termination requests when it was first introduced. As early as 2015, there was a proposal issue on Github that terminated fetch requests. There are many solutions to this problem outside of the FETCH specification, such as Cancelable-Promises and other Hacks.

Finally, the generic AbortController and AbortSignal apis are available. The API is defined in the DOM standard, not the language specification.

What is theAbortController?

DevTools outputAbortControllerfunction

The DOM document contains this passage:

Although promises do not provide a built-in aborting mechanism, many apis that use them require termination semantics. AbortController supports these requirements by providing an abort() method, which is used to switch the state of the corresponding AbortSignal object. You want an API that supports termination to accept an AbortSignal object and determine the execution process based on its state.

// Create an AbortController instance
const controller = new AbortController();
const signal = controller.signal;

// Listen for abort signal. Controller.abort () is called and this callback is triggered
signal.addEventListener('abort', () = > {console.log(signal.aborted); // true
});

// Execute the termination operation later, which notifies signal
controller.abort();
Copy the code

How to useAbortControllerTermination offetchThe request?

The second argument to the FETCH method supports the configuration of a signal option, whose value is the AbortSignal object.

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

// API returns a response after 3s
// Notice that the second argument uses a 'signal' option
fetch('https://slowmo.glitch.me/3000', { signal })
  .then(r= > r.json())
  .then(response= > console.log(response))
  .catch(err= > {
    if (err.name === 'AbortError') {
      console.log('Fetch was aborted');
    } else {
      console.error('Oops! ', err); }});// execute abort operation after 2s
// This causes the fetch request to be aborted with an 'AbortError' error.
setTimeout((a)= > {
  controller.abort();
}, 2000);
Copy the code

This method of termination includes terminating the fetch request and corresponding. Error new DOMException(‘Aborted’, ‘AbortError’) when the request fails.

In addition, the same AbortSignal (the signal used above) object can be used for multiple FETCH requests.

demo

Click on the links to view the online demo here: codesandbox. IO/s/abortable…

The demo screenshot

AbortController is not meant to be used only by fetch. It is a generic API for terminating asynchronous tasks. For example, you can use it to fulfill a Promise that can be canceled.

Browser compatibility and Polyfill

Many older browsers do not yet support the AbortController and AbortSignal apis. Here are polyfills you can use.

  • www.npmjs.com/package/abo…
  • www.npmjs.com/package/abo…

Thanks for reading and I hope this article will help you!

reference

Thank you

(End of text)


Advertising time (long term)

I have a good friend who owns a cattery, and I’m here to promote it for her. Now the cattery is full of Muppets. If you are also a cat lover and have the need, scan her FREE fish QR code. It doesn’t matter if you don’t buy it. You can just look at it.

(after)