How to cancel a Fetch request in JavaScript
In this tutorial, we are going to learn about how to cancel a fetch request by using an abort controller in JavaScript.
So far we didn’t have any built-in methods to cancel the fetch request, currently, the new AbortController
interface is added to JavaScript to abort the request by calling an abort()
method.
Cancelling the fetch request
To cancel the fetch request first we need to initialize the AbortController
constructor then it returns an object, which contains a signal
property.
Now, we need to pass the signal
property as an option to the fetch request.
At final, we need to run the abort()
method to cancel the ongoing fetch request that associates with a signal.
Example:
const cancel = document.querySelector('#cancel');
const controller = new AbortController();
const signal = controller.signal;
// abort signal is passed
fetch('https://reqres.in/api/users?delay=5',{signal}) .then(response => response.json())
.then(json => console.log(json))
.catch(err=>console.log(err.message))
cancel.addEventListener('click',()=>{
controller.abort(); // aborting request console.log('request is aborted')
})
If you click on the cancel
button, the following fetch request is canceled with an AbortError
.
You can also respond to the AbortError
like this in the catch
method.
catch(err=>{
if(err.name = 'AbortError'){ console.log(' fetch is cancelled')
} else{
console.log('other errors', err.message);
}
})
Cancelling the multiple fetch requests
We can also use the same signal to cancel the multiple fetch requests.
const cancel = document.querySelector('#cancel');
const controller = new AbortController();
const signal = controller.signal;
// abort signal is passed
fetch('https://reqres.in/api/users?delay=5',{signal}) .then(response => response.json())
.then(json => console.log(json))
.catch(err=>console.log(err.message))
fetch('https://reqres.in/api/users/2?delay=5',{signal}) .then(response => response.json())
.then(json => console.log(json))
.catch(err=>console.log(err.message))
cancel.addEventListener('click',()=>{
controller.abort(); // aborting request
console.log('request is aborted')
})