Skip to content

Instantly share code, notes, and snippets.

@skounis
Created February 5, 2019 05:59
Show Gist options
  • Save skounis/75305189fb22a4b689b7cafa245b98e4 to your computer and use it in GitHub Desktop.
Save skounis/75305189fb22a4b689b7cafa245b98e4 to your computer and use it in GitHub Desktop.
Cancel a Promise
// Adapted from:
// https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html
function cancellable(promise) {
let cancelled = false;
// Creates a wrapper promise to return. This wrapper is
// resolved or rejected based on the wrapped promise, and
// on the "cancelled" value.
const promiseWrapper = new Promise((resolve, reject) => {
promise.then(
value => {
return cancelled ? reject({ cancelled: true }) : resolve(value);
},
error => {
return cancelled
? reject({ cancelled: true })
: reject(error);
}
);
});
// Adds a "cancel()" method to the promise, for
// use by the React component in "componentWillUnmount()".
promiseWrapper.cancel = function cancel() {
cancelled = true;
};
return promiseWrapper;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment