Commit db17262e by Dominik Prokop

Add util for handling promise cancelation to avoid setting state on unmounted components

https://github.com/facebook/react/issues/5465
parent 433c88a6
// https://github.com/facebook/react/issues/5465
export interface CancelablePromise<T> {
promise: Promise<T>;
cancel: () => void;
}
export const makePromiseCancelable = <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)));
promise.catch(error => (hasCanceled_ ? reject({ isCanceled: true }) : reject(error)));
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment