Skip to content

Instantly share code, notes, and snippets.

@vvatikiotis
Last active October 2, 2018 12:42
Show Gist options
  • Save vvatikiotis/a66f809eadf0df7fbb24061bd0f71860 to your computer and use it in GitHub Desktop.
Save vvatikiotis/a66f809eadf0df7fbb24061bd0f71860 to your computer and use it in GitHub Desktop.
Cancellable promise helper
// https://github.com/mehiel/router/blob/58c7aa4d0be87b6c4aad9643f168058f42eafcd7/src/lib/utils.js#L261
// makeCancelable as in https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
const makeCancelable = promise => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
val => (hasCanceled_ ? reject({ isCanceled: true }) : resolve(val)),
error => (hasCanceled_ ? reject({ isCanceled: true }) : reject(error))
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment