What is abortcontroller-polyfill?
The abortcontroller-polyfill package provides a polyfill for the AbortController interface, which allows you to abort one or more Web requests as and when desired. This is particularly useful for canceling fetch requests in environments where the AbortController API is not natively supported, such as older browsers.
What are abortcontroller-polyfill's main functionalities?
Aborting a fetch request
This code demonstrates how to use abortcontroller-polyfill to abort a fetch request. An instance of AbortController is created, and its signal is passed to the fetch request. Calling `abort` on the controller instance will cancel the request.
const { AbortController } = require('abortcontroller-polyfill/dist/cjs-ponyfill');
let controller = new AbortController();
let signal = controller.signal;
fetch('https://example.com', { signal })
.then(response => console.log(response))
.catch(err => console.error(err));
// Abort the request
ccontroller.abort();
Other packages similar to abortcontroller-polyfill
whatwg-fetch
The whatwg-fetch package is a polyfill for the fetch API, which includes support for aborting requests using AbortController. However, it focuses more broadly on providing the fetch API rather than specifically on the abort functionality.
axios
Axios is a promise-based HTTP client for the browser and node.js that supports request cancellation. While it provides similar functionality to abort requests, it does so through its own API rather than using the AbortController interface.
AbortController "polyfill"
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 calls .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 => {
}).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, import it early in your client entrypoint .js file using
import 'abortcontroller-polyfill'
or require('abortcontroller-polyfill')
.
Contributors
- Martin Olsson
- Jimmy Karl Roland Wärting
See also
License
MIT