Home > Web Front-end > JS Tutorial > body text

How Can I Cancel a Fetch() Request in JavaScript?

Mary-Kate Olsen
Release: 2024-11-20 00:34:03
Original
1002 people have browsed it

How Can I Cancel a Fetch() Request in JavaScript?

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:

  1. Create an AbortController.
  2. Obtain the AbortController's signal.
  3. Pass the signal to fetch() as an argument.
  4. Abort the request whenever necessary.

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template