How to abort a fetch request using the AbortController
AbortController
By using the AbortController interface, we can reject a JavaScript web request.
The AbortController object contains a
To creating an Abort-able request:
- create an AbortController object
- pass the signal property of the AbortController object to the request
- call the abort method of the AbortController object to abort the request
Create an AbortController
var controller = new AbortController();
Pass the signal property to fetch
When we pass the signal property to fetch, the signal and the controller will be associated with the fetch request:
fetch(url, {signal: controller.signal}).then( (resp) => {
// ... once received
}).catch( (e) => {
console.log("Exception occured", e);
});
Calling the abort function
When we call abort, the signal will be received by the associated fetch request and the promise will reject with a DOMException named AbortError.
controller.abort();
If we call
abortafter the response is received, it will have no effect on the request.
Code
To try abort, go to Google and execute the code (below) in the Developer Tools console of your browser.
function test(abortRequest) {
var controller = new AbortController();
// url = "" - fetches home page
fetch("", {signal: controller.signal}).then( (resp) => {
console.log(resp)
}).catch( (e) => {
console.log("Exception occured", e);
});
if(abortRequest) {
controller.abort();
}
}
test();
test(true);