Created
May 1, 2018 10:36
-
-
Save vsashyn/92b4dbe4f917903d66a78c37ede4c783 to your computer and use it in GitHub Desktop.
Cancelable promise with proper handling exception on main promise
This file contains hidden or 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
// cancelable promise | |
// originaly by @istarkov | |
const makeCancelable = (promise) => { | |
let hasCanceled_ = false; | |
const wrappedPromise = new Promise((resolve, reject) => { | |
promise.then((val) => | |
hasCanceled_ ? reject({isCanceled: true}) : resolve(val), | |
error => console.warn | |
); | |
promise.catch((error) => | |
hasCanceled_ ? reject({isCanceled: true}) : reject(error) | |
); | |
}); | |
return { | |
promise: wrappedPromise, | |
cancel() { | |
hasCanceled_ = true; | |
}, | |
}; | |
}; | |
const somePromise = new Promise(r => setTimeout(r, 1000)); | |
const cancelable = makeCancelable(somePromise); | |
cancelable | |
.promise | |
.then(() => console.log('resolved')) | |
.catch(({isCanceled, ...error}) => console.log('isCanceled', isCanceled)); | |
// Cancel promise | |
cancelable.cancel(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment