Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Last active May 6, 2019 05:42
Show Gist options
  • Save NickStrupat/33a46c5b32779c356fbb533ac561900c to your computer and use it in GitHub Desktop.
Save NickStrupat/33a46c5b32779c356fbb533ac561900c to your computer and use it in GitHub Desktop.
export class QueryablePromise<T> implements Promise<T> {
private readonly promise: Promise<T>;
private _isPending: boolean = true;
private _isRejected: boolean = false;
private _isFulfilled: boolean = false;
public get isPending(): boolean { return this._isPending; };
public get isRejected(): boolean { return this._isRejected; };
public get isFulfilled(): boolean { return this._isFulfilled; };
public constructor(promise: Promise<T>) {
this.promise =
promise
.then(value => {
this._isFulfilled = true;
return value;
})
.catch(reason => {
this._isRejected = true;
return reason;
})
.finally(() => {
this._isPending = false;
});
}
then<TResult1 = T, TResult2 = never>(
onfulfilled?: (value: T) => TResult1 | PromiseLike<TResult1>,
onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>
): Promise<TResult1 | TResult2> {
return this.promise.then(onfulfilled, onrejected);
}
catch<TResult = never>(onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<T | TResult> {
return this.promise.catch(onrejected);
}
[Symbol.toStringTag]: string;
finally(onfinally?: () => void): Promise<T> {
return this.promise.finally(onfinally);
}
toString = () =>
`isPending: ${this.isPending}\n` +
`isRejected: ${this.isRejected}\n` +
`isFulfilled: ${this.isFulfilled}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment