How to cancel a Fetch request in JavaScript
In this post we will give you information about How to cancel a Fetch request in JavaScript. Hear we will give you detail about How to cancel a Fetch request in JavaScriptAnd how to use it also give you demo for it if it is necessary.
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 passedfetch('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 passedfetch('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')})
Hope this code and post will helped you for implement How to cancel a Fetch request in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs