Skip to content

Instantly share code, notes, and snippets.

Last active March 7, 2020 07:10
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ilfroloff/5c507469ae2b953089969bb40d6e5d4f to your computer and use it in GitHub Desktop.

Abortable promises and fetch() requests


Frequently requires to abort fetch request. Current realization of fetch() doesn't have this opportunity, but it can be realized by behavior of Promise.race.

You can abort or cancel any long promise or fetch.


import abortable from './AbortablePromise';

const long_request = abortable(fetch(/* url */));

    .then(() => console.log('never will be resolved'))
    .catch(err => err === 'abort');

/* ... */

const ABORTABLE_ERROR_KEY = '__abortablePromise';
* @typedef {Promise.<*>} AbortablePromise
* @property {function} abort Additional method for abort original promise
* @param {Promise} promise
* @returns {AbortablePromise}
export default function abortablePromise(promise) {
* Promise never will be resolved, but can be rejected
* @type function
let abort = null;
* Promise never will be resolved, but can be rejected
* @type Promise
const abort_promise = new Promise((resolve, reject) => {
abort = function() {
const abortable_promise = Promise
.catch(err => err === ABORTABLE_ERROR_KEY?
Promise.reject('abort') :
abortable_promise.abort = abort;
return abortable_promise;
Copy link

Interesting solution, but it does not really "cancel" the fetch request. It merely ignores the return value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment