Created
August 28, 2019 22:08
-
-
Save potatosalad/763455722fb31581c7f25c31a729ca5c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface CancellablePromise<T> extends Promise<T> { | |
cancel(reason: any): void | |
} | |
export class Cancellable { | |
public promise: Promise<never> | |
private cancelled: boolean | |
private reason?: any | |
constructor() { | |
this.cancelled = false | |
this.promise = new Promise((_resolve, reject) => { | |
if (this.cancelled === true) { | |
reject(this.reason) | |
} else { | |
const cancel = this.cancel.bind(this) | |
this.cancel = (reason: any): void => { | |
cancel(reason) | |
reject(reason) | |
} | |
} | |
}) | |
} | |
static wrap<T>(promise: Promise<T>): CancellablePromise<T> { | |
const cancellable = new Cancellable() | |
return cancellable.wrap<T>(promise) | |
} | |
cancel(reason: any): void { | |
if (this.cancelled === false) { | |
this.cancelled = true | |
this.reason = reason | |
} | |
} | |
wrap<T>(promise: Promise<T>): CancellablePromise<T> { | |
const cancellablePromise: CancellablePromise<T> = Promise.race([promise, this.promise]) as CancellablePromise<T> | |
cancellablePromise.cancel = (reason: any): void => { | |
this.cancel(reason) | |
} | |
return cancellablePromise | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment