The advent of the fetch() API for making requests from JavaScript has raised questions regarding its cancellation mechanism for in-flight requests. Historically, there were no built-in options. However, a recent update has introduced a pathway for request cancelation.
Effective September 20, 2017, fetch() now supports a signal parameter, enabling the cancelation of requests through a combination with an AbortController. The following steps outline the process:
Create an AbortController object:
Obtain the AbortController's signal:
Pass the signal to fetch():
Abort the request when necessary:
Consider the following example (compatible with Firefox 57 ):
// Create an AbortController instance. const controller = new AbortController(); const signal = controller.signal; function beginFetching() { console.log('Now fetching'); fetch("https://httpbin.org/delay/3", { 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 the request. controller.abort(); }
In this example, clicking the "Begin" button will initiate the request, while the "Abort" button will terminate it before completion.
The above is the detailed content of How Can I Cancel an In-Flight `fetch()` Request in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!