joaovieira / abortcontroller-polyfill

Browser polyfill for the AbortController DOM API (stub that calls catch, doesn't actually abort request).

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

AbortController polyfill for abortable fetch()

Minimal stubs so that the AbortController DOM API for terminating fetch() requests can be used in browsers that doesn't yet implement it. This "polyfill" doesn't actually close the connection when the request is aborted, but it will call .catch() with err.name == 'AbortError' instead of .then().

const controller = new AbortController();
const signal = controller.signal;
fetch('/some/url', {signal}).then(res => res.json()).then(data => {
  // do something with "data"
}).catch(err => {
  if (err.name == 'AbortError') {
    return;
  }
});

You can read about the AbortController API in the DOM specification.

How to use

$ npm install --save abortcontroller-polyfill

If you're using webpack or similar, you then import it early in your client entrypoint .js file using

import 'abortcontroller-polyfill'

or

require('abortcontroller-polyfill')

Using it along with 'create-react-app'

create-react-app enforces the no-undef eslint rule at compile time so if your version of eslint does not list AbortController etc as a known global for the browser environment, then you might run into an compile error like:

  'AbortController' is not defined  no-undef

This can be worked around by (temporarily, details here) adding a declaration like:

  const AbortController = window.AbortController;

Contributors

License

MIT

About

Browser polyfill for the AbortController DOM API (stub that calls catch, doesn't actually abort request).

License:MIT License


Languages

Language:JavaScript 92.4%Language:Shell 7.3%Language:HTML 0.3%