Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Last active December 11, 2018 10:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbranyen/07d5ae9b4eefd060a70dccd3a52287ad to your computer and use it in GitHub Desktop.
Save tbranyen/07d5ae9b4eefd060a70dccd3a52287ad to your computer and use it in GitHub Desktop.
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