Making Cancel-able HTTP Requests with JavaScript Fetch API
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…