Last active
November 30, 2017 19:05
-
-
Save dkarmalita/2ec6f8b60fba2c391cd401821241dee5 to your computer and use it in GitHub Desktop.
Example: Cancelable Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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