Last active
May 14, 2022 23:03
-
-
Save karol-majewski/39f03e67e09a77439f9eec1a9e2a450c to your computer and use it in GitHub Desktop.
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
/** | |
* TypeScript version of @istarkov's cancellable Promise wrapper. | |
* | |
* @see https://github.com/facebook/react/issues/5465#issuecomment-157888325 | |
*/ | |
const makeCancelable = <T>(promise: Promise<T>): { promise: Promise<T>; cancel(): void } => { | |
let hasCanceled = false; | |
const wrappedPromise = new Promise<T>((resolve, reject) => { | |
promise.then( | |
value => hasCanceled | |
? reject({ isCanceled: true }) | |
: resolve(value), | |
error => hasCanceled | |
? reject({ isCanceled: true }) | |
: reject(error), | |
); | |
}); | |
return { | |
promise: wrappedPromise, | |
cancel(): void { | |
hasCanceled = true; | |
}, | |
}; | |
}; | |
const somePromise = new Promise(resolve => setTimeout(resolve, 1000)); | |
const cancelable = makeCancelable(somePromise); | |
cancelable.promise | |
.then(console.log) | |
.catch(({ isCanceled }) => console.error('isCanceled', isCanceled)); | |
cancelable.cancel(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment