Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort a fetch request?

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

like image 736
Royi Mindel Avatar asked Feb 02 '17 07:02

Royi Mindel


Video Answer


2 Answers

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:

  1. https://developers.google.com/web/updates/2017/09/abortable-fetch
  2. https://developer.mozilla.org/en-US/docs/Web/API/AbortController
like image 105
ixrock Avatar answered Oct 23 '22 13:10

ixrock


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()
like image 36
SiggyF Avatar answered Oct 23 '22 13:10

SiggyF