Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@GFoley83
Created April 26, 2018 07:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save GFoley83/5877f6c09fbcfd62569c51dc91444cf0 to your computer and use it in GitHub Desktop.
Save GFoley83/5877f6c09fbcfd62569c51dc91444cf0 to your computer and use it in GitHub Desktop.
Deferred Promise for Typescript
/**
* 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