Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Make Cancellable Promise
Promise.makeCancellable = promise => {
const deferred = {};
const promise = new Promise((resolve, reject) => {
deferred.reject = reject;
// Invoke the fetch argument with the matching args... only resolve if not
// aborted.
promise
.then(resp => !deferred.aborted && resolve(resp))
.catch(ex => !deferred.aborted && reject(ex));
});
promise.abort = function() {
deferred.reject(null);
deferred.aborted = true;
return promise;
};
return promise;
};
// Usage...
Promise.makeCancellable(fetch('/someurl')).then(handleResponse).catch(ex => {
// Only handle real errors...
if (ex !== null) {
throw ex;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.