本文介绍了如何取消 HTTP fetch() 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个用于从 JavaScript 发出请求的新 API:fetch().是否有任何内置机制可以取消这些请求?

There is a new API for making requests from JavaScript: fetch(). Is there any built in mechanism for canceling these requests in-flight?

推荐答案

TL/DR:

自 2017 年 9 月 20 日起,

fetch 现在支持 signal 参数,但不支持目前所有浏览器似乎都支持这一点.

TL/DR:

fetch now supports a signal parameter as of 20 September 2017, but not all browsers seem support this at the moment.

2020 年更新:大多数主要浏览器(Edge、Firefox、Chrome、Safari、Opera 和其他一些浏览器)支持该功能,该功能已成为DOM 生活标准的一部分.(截至 2020 年 3 月 5 日)

2020 UPDATE: Most major browsers (Edge, Firefox, Chrome, Safari, Opera, and a few others) support the feature, which has become part of the DOM living standard. (as of 5 March 2020)

不过,这是一个我们很快就会看到的变化,因此您应该能够使用 AbortControllers AbortSignal 取消请求.

This is a change we will be seeing very soon though, and so you should be able to cancel a request by using an AbortControllers AbortSignal.

它的工作方式是这样的:

The way it works is this:

第 1 步:您创建一个 AbortController(现在我只使用了 这个)

Step 1: You create an AbortController (For now I just used this)

const controller = new AbortController()

第 2 步:您会像这样获得 AbortController 的信号:

Step 2: You get the AbortControllers signal like this:

const signal = controller.signal

第 3 步:您像这样传递 信号 来获取:

Step 3: You pass the signal to fetch like so:

fetch(urlToFetch, {
    method: 'get',
    signal: signal, // <------ This is our AbortSignal
})

第 4 步:只要需要就中止:

controller.abort();

以下是它如何工作的示例(适用于 Firefox 57+):

Here's an example of how it would work (works on Firefox 57+):

<script>
    // Create an instance.
    const controller = new AbortController()
    const signal = controller.signal

    /*
    // Register a listenr.
    signal.addEventListener("abort", () => {
        console.log("aborted!")
    })
    */


    function beginFetching() {
        console.log('Now fetching');
        var urlToFetch = "https://httpbin.org/delay/3";

        fetch(urlToFetch, {
                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.
        controller.abort()
    }

</script>



<h1>Example of fetch abort</h1>
<hr>
<button onclick="beginFetching();">
    Begin
</button>
<button onclick="abortFetching();">
    Abort
</button>
  • The final version of AbortController has been added to the DOM specification
  • The corresponding PR for the fetch specification is now merged.
  • Browser bugs tracking the implementation of AbortController is available here: Firefox: #1378342, Chromium: #750599, WebKit: #174980, Edge: #13009916.

这篇关于如何取消 HTTP fetch() 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-25 20:49