The introduction of fetch() in JavaScript has revolutionized HTTP request handling, providing a versatile and intuitive interface. However, concerns often arise regarding the ability to terminate these requests prematurely.
As of September 2017, fetch() incorporated a significant enhancement: support for the signal parameter. This parameter allows developers to cancel requests using an AbortController and its corresponding AbortSignal. Initially, browser support was limited, but now (as of March 2020), most major browsers (Edge, Firefox, Chrome, Safari, Opera, and others) fully embrace this functionality.
The cancelation process involves four steps:
const controller = new AbortController()
const signal = controller.signal
fetch(urlToFetch, { method: 'get', signal: signal, })
controller.abort();
To illustrate how it works in practice, consider the following example:
// Create an instance. const controller = new AbortController() const signal = controller.signal /* // Register a listenr. signal.addEventListener("abort", () => { console.log("aborted!") }) */ function beginFetching() { console.log('Now fetching'); var urlToFetch = "https://httpbin.org/delay/3"; fetch(urlToFetch, { method: 'get', signal: signal, }) .then(function(response) { console.log(`Fetch complete. (Not aborted)`); }).catch(function(err) { console.error(` Err: ${err}`); }); } function abortFetching() { console.log('Now aborting'); // Abort. controller.abort() }
By invoking controller.abort(), the request can be interrupted at any time.
The above is the detailed content of How Can I Interrupt HTTP Fetch Requests in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!