Skip to content

Instantly share code, notes, and snippets.

@potatosalad
Created August 28, 2019 22:08
Show Gist options
  • Save potatosalad/763455722fb31581c7f25c31a729ca5c to your computer and use it in GitHub Desktop.
Save potatosalad/763455722fb31581c7f25c31a729ca5c to your computer and use it in GitHub Desktop.
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