forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcancelable-promise.ts
32 lines (26 loc) · 1.06 KB
/
cancelable-promise.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Core Grafana history https://github.com/grafana/grafana/blob/v11.0.0-preview/public/app/core/utils/CancelablePromise.ts
// https://github.com/facebook/react/issues/5465
export interface CancelablePromise<T> {
promise: Promise<T>;
cancel: () => void;
}
export interface CancelablePromiseRejection {
isCanceled: boolean;
}
export function isCancelablePromiseRejection(promise: unknown): promise is CancelablePromiseRejection {
return typeof promise === 'object' && promise !== null && 'isCanceled' in promise;
}
export const makePromiseCancelable = <T>(promise: Promise<T>): CancelablePromise<T> => {
let hasCanceled_ = false;
const wrappedPromise = new Promise<T>((resolve, reject) => {
const canceledPromiseRejection: CancelablePromiseRejection = { isCanceled: true };
promise.then((val) => (hasCanceled_ ? reject(canceledPromiseRejection) : resolve(val)));
promise.catch((error) => (hasCanceled_ ? reject(canceledPromiseRejection) : reject(error)));
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};