Canceling HTTP Fetch() Requests: A Step-by-Step Guide
The new fetch() API for JavaScript allows developers to make HTTP requests efficiently. However, questions arise about the possibility of canceling in-flight requests. While there was no built-in mechanism initially, a new feature has recently been introduced: the signal parameter.
TL/DR:
As of September 2017, fetch() introduced the signal parameter. However, browser support varies.
2020 UPDATE:
Most major browsers now support the signal parameter (Edge, Firefox, Chrome, Safari, Opera, etc.).
How It Works:
Example:
const controller = new AbortController(); const signal = controller.signal; fetch(urlToFetch, { method: 'get', signal: signal, }) .then(function(response) { console.log(`Fetch complete. (Not aborted)`); }).catch(function(err) { console.error(` Err: ${err}`); }); controller.abort();
Please note that browser support for this feature may vary. However, as browsers continue to update, widespread support for canceling fetch() requests is expected to become available soon.
The above is the detailed content of How Can I Cancel a Fetch() Request in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!