mtcute/packages/core/src/utils/controllable-promise.ts

51 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-08-29 16:22:57 +03:00
/**
* A promise that can be resolved or rejected from outside.
*/
export type ControllablePromise<T = any> = Promise<T> & {
2021-04-08 12:19:38 +03:00
resolve(val: T): void
reject(err?: unknown): void
2021-04-08 12:19:38 +03:00
}
2022-08-29 16:22:57 +03:00
/**
* A promise that can be cancelled.
*/
export type CancellablePromise<T = any> = Promise<T> & {
cancel(): void
}
2022-08-29 16:22:57 +03:00
/**
* The promise was cancelled
*/
export class PromiseCancelledError extends Error {}
2022-08-29 16:22:57 +03:00
/**
* Creates a promise that can be resolved or rejected from outside.
*/
export function createControllablePromise<T = any>(): ControllablePromise<T> {
2021-04-08 12:19:38 +03:00
let _resolve: any
let _reject: any
const promise = new Promise<T>((resolve, reject) => {
_resolve = resolve
_reject = reject
})
;(promise as ControllablePromise<T>).resolve = _resolve
;(promise as ControllablePromise<T>).reject = _reject
return promise as ControllablePromise<T>
}
2022-08-29 16:22:57 +03:00
/**
* Creates a promise that can be cancelled.
*
* @param onCancel Callback to call when cancellation is requested
*/
export function createCancellablePromise<T = any>(
onCancel: () => void
): ControllablePromise<T> & CancellablePromise<T> {
const promise = createControllablePromise()
;(promise as unknown as CancellablePromise<T>).cancel = () => {
promise.reject(new PromiseCancelledError())
onCancel()
}
return promise as ControllablePromise<T> & CancellablePromise<T>
}