Last active
December 24, 2017 18:26
-
-
Save RomkeVdMeulen/93588812a964f842a73631a22cd9b9ad to your computer and use it in GitHub Desktop.
A Typescript utility classes for working with promises that are resolved elsewhere.
This file contains hidden or 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
/** | |
* @see https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md | |
*/ | |
export class Deferred<T> { | |
public promise: Promise<T>; | |
private fate: "resolved" | "unresolved"; | |
private state: "pending" | "fulfilled" | "rejected"; | |
private _resolve: Function; | |
private _reject: Function; | |
constructor() { | |
this.state = "pending"; | |
this.fate = "unresolved"; | |
this.promise = new Promise((resolve, reject) => { | |
this._resolve = resolve; | |
this._reject = reject; | |
}); | |
this.promise.then( | |
() => this.state = "fulfilled", | |
() => this.state = "rejected" | |
); | |
} | |
resolve(value?: any) { | |
if (this.fate === "resolved") { | |
throw "Deferred cannot be resolved twice"; | |
} | |
this.fate = "resolved"; | |
this._resolve(value); | |
} | |
reject(reason?: any) { | |
if (this.fate === "resolved") { | |
throw "Deferred cannot be resolved twice"; | |
} | |
this.fate = "resolved"; | |
this._reject(reason); | |
} | |
isResolved() { | |
return this.fate === "resolved"; | |
} | |
isPending() { | |
return this.state === "pending"; | |
} | |
isFulfilled() { | |
return this.state === "fulfilled"; | |
} | |
isRejected() { | |
return this.state === "rejected"; | |
} | |
} |
This file contains hidden or 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
class DeferredDemo { | |
private deferred = new Deferred<MyType>(); | |
givePromise() { | |
return this.deferred.promise; | |
} | |
private fulfillPromise(value: MyType) { | |
if (this.deferred.isResolved()) { | |
return; | |
} | |
this.deferred.resolve(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment