I've been using the new fetch API instead of the old XMLHttpRequest
It is great but I am missing one crucial function, xhr.abort().
I can't find any information about that functionality for fetch.
Thanks.
UPDATE: hacky workaround for aborting fetch 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
It's possible to abort fetch via 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:
I typically use something like this, similar to @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()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With