Created
May 12, 2021 11:44
-
-
Save marionebl/d5f892336de853bdc9cf48b34c8043ff to your computer and use it in GitHub Desktop.
This file contains 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
class Deferrable<T> implements Promise<T> { | |
private promise: Promise<T>; | |
private resolver!: (value: T | PromiseLike<T>) => void; | |
private rejecter!: (reason?: any) => void; | |
public constructor() { | |
this.promise = new Promise((resolver, rejecter) => { | |
this.resolver = resolver; | |
this.rejecter = rejecter; | |
}); | |
} | |
[Symbol.toStringTag]: 'Deferrable'; | |
public resolve(value: T | PromiseLike<T>): void { | |
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
this.resolver!(value); | |
} | |
public reject(reason?: any): void { | |
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
this.rejecter!(reason); | |
} | |
public async unwrap(): Promise<T> { | |
return this.promise; | |
} | |
public then<TResult1 = T, TResult2 = never>( | |
onfulfilled?: | |
| ((value: T) => TResult1 | PromiseLike<TResult1>) | |
| undefined | |
| null, | |
onrejected?: | |
| ((reason: any) => TResult2 | PromiseLike<TResult2>) | |
| undefined | |
| null, | |
): Promise<TResult1 | TResult2> { | |
return this.promise.then(onfulfilled, onrejected); | |
} | |
public catch<TResult = never>( | |
onrejected?: | |
| ((reason: any) => TResult | PromiseLike<TResult>) | |
| undefined | |
| null, | |
): Promise<T | TResult> { | |
return this.promise.catch(onrejected); | |
} | |
public finally(onfinally?: (() => void) | undefined | null): Promise<T> { | |
return this.promise.finally(onfinally); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment