简体   繁体   English

如何中止获取请求?

[英]How to abort a fetch request?

I've been using the new fetch API instead of the oldXMLHttpRequest我一直在使用新的fetch API而不是旧的XMLHttpRequest

It is great but I am missing one crucial function, xhr.abort() .这很棒,但我缺少一个关键功能, xhr.abort()

I can't find any information about that functionality for fetch.我找不到有关该 fetch 功能的任何信息。

Thanks.谢谢。

UPDATE: hacky workaround for aborting fetch https://github.com/Morantron/poor-mans-cancelable-fetch更新:中止获取的hacky解决方法https://github.com/Morantron/poor-mans-cancelable-fetch

Basically you start the fetch in a web worker and cancel the web worker to abort the fetch基本上,您在网络工作者中启动提取并取消网络工作者以中止提取

Its still an open issue All relevant discussion can be found here它仍然是一个悬而未决的问题所有相关讨论都可以在这里找到

https://github.com/whatwg/fetch/issues/447 :( https://github.com/whatwg/fetch/issues/447 :(

It's possible to abort fetch via AbortController :可以通过AbortController中止获取:

export function cancelableFetch(reqInfo, reqInit) {
  var abortController = new AbortController();
  var signal = abortController.signal;
  var cancel = abortController.abort.bind(abortController);

  var wrapResult = function (result) {
    if (result instanceof Promise) {
      var promise = result;
      promise.then = function (onfulfilled, onrejected) {
        var nativeThenResult = Object.getPrototypeOf(this).then.call(this, onfulfilled, onrejected);
        return wrapResult(nativeThenResult);
      }
      promise.cancel = cancel;
    }
    return result;
  }

  var req = window.fetch(reqInfo, Object.assign({signal: signal}, reqInit));
  return wrapResult(req);
}

Usage example:用法示例:

var req = cancelableFetch("/api/config")
  .then(res => res.json())
  .catch(err => {
    if (err.code === DOMException.ABORT_ERR) {
      console.log('Request canceled.')
    }
    else {
      // handle error
    }
  });

setTimeout(() => req.cancel(), 2000);

Links:链接:

  1. https://developers.google.com/web/updates/2017/09/abortable-fetch https://developers.google.com/web/updates/2017/09/abortable-fetch
  2. https://developer.mozilla.org/en-US/docs/Web/API/AbortController https://developer.mozilla.org/en-US/docs/Web/API/AbortController

I typically use something like this, similar to @ixrock.我通常使用类似这样的东西,类似于@ixrock。

// Fetch and return the promise with the abort controller as controller property
function fetchWithController(input, init) {
  // create the controller
  let controller = new AbortController()
  // use the signal to hookup the controller to the fetch request
  let signal = controller.signal
  // extend arguments
  init = Object.assign({signal}, init)
  // call the fetch request
  let promise = fetch(input, init)
  // attach the controller
  promise.controller = controller
  return promise
}

and then replace a normal fetch with然后用

let promise = fetchWithController('/')
promise.controller.abort()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM