Skip to content

Instantly share code, notes, and snippets.

@ilfroloff
Last active March 7, 2020 07:10
Show Gist options
  • Save ilfroloff/5c507469ae2b953089969bb40d6e5d4f to your computer and use it in GitHub Desktop.
Save ilfroloff/5c507469ae2b953089969bb40d6e5d4f to your computer and use it in GitHub Desktop.

Abortable promises and fetch() requests

Description

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.

Usage

import abortable from './AbortablePromise';

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

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

/* ... */

long_request.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() {
reject(ABORTABLE_ERROR_KEY);
};
});
const abortable_promise = Promise
.race([
promise,
abort_promise
])
.catch(err => err === ABORTABLE_ERROR_KEY?
Promise.reject('abort') :
Promise.reject(err)
);
abortable_promise.abort = abort;
return abortable_promise;
}
@Amberlamps
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