Created
October 3, 2016 14:28
-
-
Save rwhitmire/f4422e0284614b96ff8459fa1e2ce75b to your computer and use it in GitHub Desktop.
Cancelable Promises
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
// source: 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