Created
October 27, 2018 06:20
-
-
Save 197291/79f8b21f9539dd76dd2acb2048969b1c to your computer and use it in GitHub Desktop.
Cancelable 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
export interface CancelablePromise<T> { | |
promise: Promise<T>; | |
cancel(): void; | |
} | |
/** | |
* Make a Promise cancelable | |
*/ | |
export const makeCancelablePromise = <T>(promise: Promise<T>): CancelablePromise<T> => { | |
let hasCanceled = false; | |
const wrappedPromise = new Promise<T>((resolve, reject) => { | |
promise.then( | |
val => hasCanceled ? reject({ isCanceled: true }) : resolve(val), | |
error => hasCanceled ? reject({ isCanceled: true }) : reject(error) | |
); | |
}); | |
return { | |
promise: wrappedPromise, | |
cancel() { | |
hasCanceled = true; | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment