Skip to content

Instantly share code, notes, and snippets.

@odbol
Created Aug 4, 2022
Embed
What would you like to do?
Deferred: a Promise that you can resolve or reject after the fact.
/**
* A Promise that you can resolve or reject after the fact.
*/
export class Deferred<T> {
private _resolve?: (result: T) => void;
private _reject?: (error: Error) => void;
promise: Promise<T>;
constructor() {
this.promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
this.reject = this.reject.bind(this);
this.resolve = this.resolve.bind(this);
}
resolve(result: T) {
this._resolve!!(result);
}
reject(error: Error) {
this._reject!!(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment