Last active
April 5, 2025 01:34
-
-
Save xantiagoma/5c4cbf8de8b6f7294dfb6906819d8a58 to your computer and use it in GitHub Desktop.
This file contains 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
export class Completer<T = unknown, E = unknown> { | |
private _promise: Promise<T>; | |
private _resolve!: (value: T | PromiseLike<T>) => void; | |
private _reject!: (reason?: E) => void; | |
constructor() { | |
this._promise = new Promise<T>((resolve, reject) => { | |
this._resolve = resolve; | |
this._reject = reject; | |
}); | |
} | |
public resolve(value: T): void { | |
this._resolve(value); | |
} | |
public reject(reason: E): void { | |
this._reject(reason); | |
} | |
public promise(): Promise<T> { | |
return this._promise; | |
} | |
public reset() { | |
this._promise = new Promise<T>((resolve, reject) => { | |
this._resolve = resolve; | |
this._reject = reject; | |
}); | |
} | |
} | |
// Example usage with default types (T and E as unknown) | |
const completer1 = new Completer(); | |
// Example usage with a specific type for value and error | |
const completer2 = new Completer<number, string>(); | |
completer1.promise().then( | |
(value) => console.log("Resolved with unknown value:", value), | |
(error) => console.log("Rejected with unknown error:", error) | |
); | |
completer2.promise().then( | |
(value) => console.log("Resolved with number value:", value), | |
(error) => console.log("Rejected with string error:", error) | |
); | |
// Resolve and reject examples | |
setTimeout(() => { | |
completer1.resolve("A string value"); // Completer1 resolves with a string (unknown type) | |
}, 1000); | |
setTimeout(() => { | |
completer2.resolve(42); // Completer2 resolves with a number | |
}, 2000); | |
setTimeout(() => { | |
completer2.reject("An error occurred"); // Completer2 rejects with a string | |
}, 3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment