Created
August 4, 2022 23:06
-
-
Save odbol/1a98cf6186caaace78cae9e7a249c992 to your computer and use it in GitHub Desktop.
Deferred: a Promise that you can resolve or reject after the fact.
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
/** | |
* 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