-
-
Save leadwolfx/2425a335ff01c46c4a43b265f734f1c7 to your computer and use it in GitHub Desktop.
Deferred Promise for Typescript
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
| /** | |
| * A new instance of deferred is constructed by calling `new DeferredPromse<T>()`. | |
| * The purpose of the deferred object is to expose the associated Promise | |
| * instance APIs that can be used for signaling the successful | |
| * or unsuccessful completion, as well as the state of the task. | |
| * @export | |
| * @class DeferredPromise | |
| * @implements {Promise<T>} | |
| * @template T | |
| * @example | |
| * const deferred = new DeferredPromse<string>(); | |
| * console.log(deferred.state); // 'pending' | |
| * | |
| * deferred | |
| * .then(str => console.log(str)) | |
| * .catch(err => console.error(err)); | |
| * | |
| * deferred.resolve('Foo'); | |
| * console.log(deferred.state); // 'fulfilled' | |
| * // deferred.reject('Bar'); | |
| */ | |
| export class DeferredPromise<T> implements Promise<T> { | |
| [Symbol.toStringTag]: 'Promise'; | |
| private readonly _promise: Promise<T>; | |
| private _resolve!: (value: T | PromiseLike<T>) => void; | |
| private _reject!: (reason?: any) => void; | |
| private _state: 'pending' | 'fulfilled' | 'rejected' = 'pending'; | |
| public get state(): 'pending' | 'fulfilled' | 'rejected' { | |
| return this._state; | |
| } | |
| constructor() { | |
| this._promise = new Promise<T>((resolve, reject) => { | |
| this._resolve = resolve; | |
| this._reject = reject; | |
| }); | |
| } | |
| public async then<TResult1, TResult2>( | |
| onfulfilled?: (value: T) => TResult1 | PromiseLike<TResult1>, | |
| onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2> | |
| ): Promise<TResult1 | TResult2> { | |
| return await this._promise.then(onfulfilled, onrejected); | |
| } | |
| public async catch<TResult>( | |
| onrejected?: (reason: any) => TResult | PromiseLike<TResult> | |
| ): Promise<T | TResult> { | |
| return await this._promise.catch(onrejected); | |
| } | |
| public resolve(value: T | PromiseLike<T>): void { | |
| this._resolve(value); | |
| this._state = 'fulfilled'; | |
| } | |
| public reject(reason?: any): void { | |
| this._reject(reason); | |
| this._state = 'rejected'; | |
| } | |
| public async finally(onfinally: (() => void) | undefined | null): Promise<T> { | |
| return await this._promise.finally(onfinally); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment