Skip to content

Instantly share code, notes, and snippets.

@jhunterkohler
Created July 1, 2022 19:04
Show Gist options
  • Save jhunterkohler/6d17b6cf8713752a39a850584c280520 to your computer and use it in GitHub Desktop.
Save jhunterkohler/6d17b6cf8713752a39a850584c280520 to your computer and use it in GitHub Desktop.
class PromiseHandle<T> {
private _resolve!: (value: T | PromiseLike<T>) => void;
private _reject!: (reason?: unknown) => void;
private _promise: Promise<T>;
private _resolved: boolean = false;
private _rejected: boolean = false;
public constructor() {
this._promise = new Promise<T>((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
}
private _check() {
if (this._resolved) {
throw new TypeError("PromiseHandle previously resolved");
} else if (this._rejected) {
throw new TypeError("PromiseHandle previously rejected");
}
}
public resolve(value: T | PromiseLike<T>) {
this._check();
this._resolved = true;
this._resolve(value);
}
public reject(reason?: unknown) {
this._check();
this._rejected = true;
this._reject(reason);
}
public get promise() {
return this._promise;
}
public get resolved() {
return this._resolved;
}
public get rejected() {
return this._rejected;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment