首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何取消HTTP fetch()请求?

如何取消HTTP fetch()请求?
EN

Stack Overflow用户
提问于 2015-06-26 06:23:29
回答 6查看 125.3K关注 0票数 257

有一个新的接口用于从JavaScript发出请求:fetch()。有没有内置的机制来取消这些正在进行中的请求?

EN

回答 6

Stack Overflow用户

发布于 2017-10-17 16:03:18

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

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

代码语言:javascript
复制
// 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();

适用于edge 16 (2017-10-17)、firefox 57 (2017-11-14)、desktop safari 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

代码语言:javascript
复制
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
票数 28
EN

Stack Overflow用户

发布于 2018-02-23 00:53:36

从2018年2月起,在Chrome上可以使用以下代码取消fetch() (请阅读Using Readable Streams以启用对火狐的支持)。在完全采用AbortController之前,不会抛出任何错误供catch()拾取,这是一个临时解决方案。

代码语言:javascript
复制
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();
        })
      }
    }
  }
}
票数 5
EN

Stack Overflow用户

发布于 2017-09-13 02:17:00

正如@spro所说,目前还没有合适的解决方案。

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

代码语言:javascript
复制
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();
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31061838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档