如何中止获取请求?

时间:2017-02-02 07:53:14

标签: javascript ecmascript-6

我一直在使用新的fetch API而不是旧的XMLHttpRequest

很棒,但我错过了一个关键功能,xhr.abort()

我找不到有关fetch功能的任何信息。

感谢。

更新: hacking fetch https://github.com/Morantron/poor-mans-cancelable-fetch

的hacky变通方法

基本上,您在Web worker中启动提取并取消Web worker以中止提取

3 个答案:

答案 0 :(得分:14)

它仍然是一个悬而未决的问题 所有相关的讨论都可以在这里找到

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

答案 1 :(得分:1)

可以通过 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);
}

用法示例:

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);

链接:

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

答案 2 :(得分:0)

我通常使用类似@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
}

,然后用

替换常规提取
let promise = fetchWithController('/')
promise.controller.abort()