Skip to content

Instantly share code, notes, and snippets.

@dkarmalita
Last active November 30, 2017 19:05
Show Gist options
  • Save dkarmalita/2ec6f8b60fba2c391cd401821241dee5 to your computer and use it in GitHub Desktop.
Save dkarmalita/2ec6f8b60fba2c391cd401821241dee5 to your computer and use it in GitHub Desktop.
Example: Cancelable Promise
// The idea is taken from: https://facebook.github.io/react/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)
);
promise.catch((error) =>
hasCanceled_ ? reject({isCanceled: true}) : reject(error)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
const cancelablePromise = makeCancelable(
new Promise(r => component.setState({...}}))
);
cancelablePromise
.promise
.then(() => console.log('resolved'))
.catch((reason) => console.log('isCanceled', reason.isCanceled));
cancelablePromise.cancel(); // Cancel the promise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment