By using the AbortController interface, we can reject a JavaScript web request.
The AbortController object contains a
To creating an Abort-able request:
var controller = new AbortController();
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);
});
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
abort
after the response is received, it will have no effect on the request.
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);