Categories
JavaScript

Making Cancel-able HTTP Requests with JavaScript Fetch API

Spread the love

The Fetch API is a big step forward from the old XMLHttpRequest object for making HTTP requests. Now it’s even better with the addition of the AbortController , which lets us make cancelable HTTP requests, which isn’t possible before.

In this article, we’ll look at how to combine the Fetch API with the new AbortController to create cancelable HTTP requests.

**AbortController and Fetch**

We can use the AbortController to create cancellable HTTP requests. To do this, we create a new AbortController using the AbortController.AbortController() constructor. Then communication with the DOM is done using the AbortSignal object.

Then using the AbortController.signal property we can get the reference to the AbortSignal object, which can be passed into the fetch function to abort an HTTP request.

For instance, we can make a GET request to download a video that can be called by writing the following code. First we create buttons for initiating the request and canceling the request when clicked as follows:

<button class='download'>
  Download
</button>
<button class='abort'>
  Abort
</button>

Then we can make our cancelable request as follows:

const controller = new AbortController();
const signal = controller.signal;
const downloadBtn = document.querySelector('.download');
const abortBtn = document.querySelector('.abort');

const fetchVideo = async () => {
  try {
    const url = 'https://sample-videos.com/video123/mp4/240/big_buck_bunny_240p_30mb.mp4';
    const response = await fetch(url, {
      signal
    });
  } catch (e) {
    console.log(e.message);
  }
}

downloadBtn.addEventListener('click', fetchVideo);

abortBtn.addEventListener('click', function() {
  controller.abort();
  console.log('Download aborted');
});

In the code above, we have the first 2 lines:

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

which creates the AbortController object and then get the AbortSignal object assign it to the signal constant. The AbortSignal sends the cancelation request.

Then in the fetchVideo function, we pass in the signal into the object that’s in the 2nd argument of fetch .

Next, we hook up the buttons to our click handler for each button by writing:

downloadBtn.addEventListener('click', fetchVideo);

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

Now when we click the Download button and then click Abort before the download is done, we’ll see Download aborted and `The user aborted a request’ show in the console log. In the Network tab of Chrome’s developer console, we’ll see that our request’s status is canceled.

Compatibility

AbortController is still considered an experimental object. However, it’s available in the latest Chromium browsers like Chrome. It’s also available on Edge, Safari, and Firefox.

It’s not available in Internet Explorer so we can use it there.

Conclusion

We can use the AbortController object and the associated AbortSignal with the Fetch API to make cancelable HTTP requests. Once the AbortSignal is sent, the HTTP request is canceled and won’t be sent if the cancellation signal is sent before the HTTP request is done.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *