如何取消HTTP fetch()请求?

问题描述 投票:146回答:5

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

javascript ajax fetch-api
5个回答
195
投票

TL/DR:

fetch现在支持2017年9月20日的signal参数,但并非所有浏览器都支持此atm。

这是我们很快就会看到的变化,因此您应该可以使用AbortControllers AbortSignal取消请求。

Long Version

How to:

它的工作方式是这样的:

第1步:你创建一个AbortController(现在我只使用this

const controller = new AbortController()

第2步:你得到这样的AbortControllers信号:

const signal = controller.signal

第3步:你将signal传递给fetch:

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

第4步:在需要时立即中止:

controller.abort();

以下是它如何工作的示例(适用于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>

Sources:


58
投票

我不相信有一种方法可以使用现有的fetch API取消请求。在https://github.com/whatwg/fetch/issues/27正在讨论它

2017年5月更新:仍无法解决。请求无法取消。在https://github.com/whatwg/fetch/issues/447进行更多讨论


13
投票

https://developers.google.com/web/updates/2017/09/abortable-fetch

https://dom.spec.whatwg.org/#aborting-ongoing-activities

// setup AbortController
const controller = new AbortController();
// signal to pass to fetch
const signal = controller.signal;

// fetch as usual
fetch(url, { signal }).then(response => {
  ...
}).catch(e => {
  // catch the abort if you like
  if (e.name === 'AbortError') {
    ...
  }
});

// when you want to abort
controller.abort();

在边缘16(2017-10-17),firefox 57(2017-11-14),桌面游猎11.1(2018-03-29),ios safari 11.4(2018-03-29),chrome 67(2018-05)工作-29),以及之后。


在较旧的浏览器上,您可以使用github's whatwg-fetch polyfillAbortController polyfill。你也可以detect older browsers and use the polyfills conditionally

import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
import {fetch} from 'whatwg-fetch'

// use native browser implementation if it supports aborting
const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch

6
投票

截至2018年2月,fetch()可以通过Chrome下面的代码取消(阅读Using Readable Streams以启用Firefox支持)。 catch()没有错误提起,这是一个临时的解决方案,直到完全采用AbortController

fetch('YOUR_CUSTOM_URL')
.then(response => {
  if (!response.body) {
    console.warn("ReadableStream is not yet supported in this browser.  See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream")
    return response;
  }

  // get reference to ReadableStream so we can cancel/abort this fetch request.
  const responseReader = response.body.getReader();
  startAbortSimulation(responseReader);

  // Return a new Response object that implements a custom reader.
  return new Response(new ReadableStream(new ReadableStreamConfig(responseReader)));
})
.then(response => response.blob())
.then(data => console.log('Download ended. Bytes downloaded:', data.size))
.catch(error => console.error('Error during fetch()', error))


// Here's an example of how to abort request once fetch() starts
function startAbortSimulation(responseReader) {
  // abort fetch() after 50ms
  setTimeout(function() {
    console.log('aborting fetch()...');
    responseReader.cancel()
    .then(function() {
      console.log('fetch() aborted');
    })
  },50)
}


// ReadableStream constructor requires custom implementation of start() method
function ReadableStreamConfig(reader) {
  return {
    start(controller) {
      read();
      function read() {
        reader.read().then(({done,value}) => {
          if (done) {
            controller.close();
            return;
          }
          controller.enqueue(value);
          read();
        })
      }
    }
  }
}

3
投票

至于现在没有适当的解决方案,正如@spro所说。

但是,如果您有正在进行的响应并且正在使用ReadableStream,则可以关闭该流以取消该请求。

fetch('http://example.com').then((res) => {
  const reader = res.body.getReader();

  /*
   * Your code for reading streams goes here
   */

  // To abort/cancel HTTP request...
  reader.cancel();
});
© www.soinside.com 2019 - 2024. All rights reserved.