Skip to content

Commit

Permalink
Add util for handling promise cancelation to avoid setting state on u…
Browse files Browse the repository at this point in the history
…nmounted components

facebook/react#5465
  • Loading branch information
dprokop committed Jan 29, 2019
1 parent 433c88a commit db17262
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions public/app/core/utils/CancelablePromise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// 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;
},
};
};

0 comments on commit db17262

Please sign in to comment.