mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Add util for handling promise cancelation to avoid setting state on unmounted components
https://github.com/facebook/react/issues/5465
This commit is contained in:
parent
433c88a616
commit
db17262ea4
22
public/app/core/utils/CancelablePromise.ts
Normal file
22
public/app/core/utils/CancelablePromise.ts
Normal file
@ -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;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
Loading…
Reference in New Issue
Block a user