Created
April 26, 2018 07:37
-
-
Save GFoley83/5877f6c09fbcfd62569c51dc91444cf0 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 _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 then<TResult1, TResult2>( | |
onfulfilled?: (value: T) => TResult1 | PromiseLike<TResult1>, | |
onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) | |
: Promise<TResult1 | TResult2> { | |
return this._promise.then(onfulfilled, onrejected); | |
} | |
public catch<TResult>(onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<T | TResult> { | |
return 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'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment