Canceling Fetch Requests: Exploring Built-in Mechanisms
JavaScript's new fetch() API provides a convenient way to make HTTP requests. However, a long-standing question remains: is there a built-in mechanism for canceling these requests mid-flight?
The Signal Parameter
As of September 2017, fetch() supports the signal parameter. This parameter accepts an AbortSignal object, which enables the controlled abortion of a fetch request.
Implementation
To cancel a fetch request, follow these steps:
Example
Consider the following code snippet:
// Initialize an AbortController and its AbortSignal const controller = new AbortController(); const signal = controller.signal; // Perform a fetch request with the AbortSignal fetch(urlToFetch, { signal, }); // Abort the request at any time controller.abort();
Browser Support
Initially, support for AbortSignal was limited. However, as of March 2020, most major browsers (Edge, Firefox, Chrome, Safari, Opera, etc.) have implemented this feature, making it a widely accessible solution.
While not all browsers may currently support AbortSignal, its widespread availability indicates that canceling fetch requests in-flight is now a commonplace capability in JavaScript development.
The above is the detailed content of How Can I Cancel Fetch Requests in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!