Skip to content

Instantly share code, notes, and snippets.

@eisisig
Forked from ilfroloff/AbortablePromise.js
Created August 30, 2016 16:10
Show Gist options
  • Save eisisig/45696617d8e44804639bbda2ee705f31 to your computer and use it in GitHub Desktop.
Save eisisig/45696617d8e44804639bbda2ee705f31 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment