For the minimum bundle size I prefer the first one and because we based on the standard AbortController API we do not need to polyfill fetch additionally:
npm i abortcontroller-polyfill
yarn add abortcontroller-polyfill
pnpm add abortcontroller-polyfill
Do not forget to exclude transpiled polyfill code from the Babel transpile:
exclude: [ "node_modules/**" ], or exclude: [ "node_modules/abortcontroller-polyfill/**" ],
Usage example
let abortController
// abort can be called as many times as you want (it run only ones)
const abort = () => abortController && abortController.abort()
const doFetch = () => {
abort() // abort the previous / ongoing call
abortController = new AbortController()
fetch('http://api.plos.org/search?q=title:DNA',
{ credentials: 'same-origin', signal: abortController.signal }).
then(response => {
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`)
}
return response.json()
}).
then(data => {
console.log('REQUEST FINISHED')
console.dir(data)
}).
catch(error => {
if (error.name === 'AbortError') {
console.log('REQUEST ABORTED')
} else {
console.error(`REQUEST FAILED: ${error ? error.message : ''}`)
}
/* The alternative way to distinct the AbortError */
if (abortController.signal.aborted) {
console.log('REQUEST ABORTED')
} else {
console.error(`REQUEST FAILED: ${error ? error.message : ''}`)
}
})
}
doFetch()
setTimeout(abort, 5000)
P.S. @developit, @prk3, @simonbuerger, @prabirshrestha PR, tests and discussion are welcome :smile:
Resolves #54 Alternative to #68, and #137
This solution
abort()
for the several parallel fetch requestsPromise.race
surrogates)AbortController
implementation (can run with polyfills on IE, see below)readyState === DONE_STATE
)include
but forsame-origin
also (usefull for some CORS use cases)unfetch
enchancement and this implementation alternativeNot sure about 500 bytes of the bundle size, but should be very close to it :wink:
The code (
abortable-unfetch.mjs
)The polyfill (
abortable-unfetch-polyfill.mjs
)AbortController
polyfillsThere are two alternatives to polyfill the standard
AbortController
behaviour on the old browsers (like IE11):abortcontroller-polyfill
abort-controller
For the minimum bundle size I prefer the first one and because we based on the standard AbortController API we do not need to polyfill fetch additionally:
Then somewhere in your
index.mjs
:Do not forget to exclude transpiled polyfill code from the Babel transpile:
exclude: [ "node_modules/**" ],
orexclude: [ "node_modules/abortcontroller-polyfill/**" ],
Usage example
P.S. @developit, @prk3, @simonbuerger, @prabirshrestha PR, tests and discussion are welcome :smile: