Home > Web Front-end > JS Tutorial > How Can I Cancel an In-Flight `fetch()` Request in JavaScript?

How Can I Cancel an In-Flight `fetch()` Request in JavaScript?

Patricia Arquette
Release: 2024-11-21 00:35:15
Original
834 people have browsed it

How Can I Cancel an In-Flight `fetch()` Request in JavaScript?

Canceling an In-Flight HTTP fetch() Request

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.

Using an AbortController

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:

  1. Create an AbortController object:

    • const controller = new AbortController()
  2. Obtain the AbortController's signal:

    • const signal = controller.signal
  3. Pass the signal to fetch():

    • fetch(urlToFetch, { method: 'get', signal: signal })
  4. Abort the request when necessary:

    • controller.abort()

Example Usage

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

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!

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