Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

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

This comment has been minimized.

Copy link

@Amberlamps Amberlamps commented Sep 1, 2016

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