Skip to content

Instantly share code, notes, and snippets.

@odbol
Created August 4, 2022 23:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odbol/1a98cf6186caaace78cae9e7a249c992 to your computer and use it in GitHub Desktop.
Save odbol/1a98cf6186caaace78cae9e7a249c992 to your computer and use it in GitHub Desktop.
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