Last active
October 23, 2019 13:18
-
-
Save TheCrafter/eb32496eaa050e0fa616705789c4df6c to your computer and use it in GitHub Desktop.
A wrapper around promises that allows for easy chaining them together.
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
/** | |
* Created by Dimitris Vlachakis (TheCrafter) on 23/10/2019 | |
* https://github.com/TheCrafter | |
* https://gist.github.com/TheCrafter/eb32496eaa050e0fa616705789c4df6c | |
* | |
* A wrapper around promises that allows for easy chaining them together. | |
* | |
* Example usage: | |
* {code} | |
* const pc = new PromiseChain<number>(125); | |
* pc.append(async (n) => { log(n); return n + 5; }) | |
* pc.append(async (n) => { log(n); throw ("wtf"); }) | |
* pc.append(async (n) => { log(n); return n + 5; }) | |
* pc.append(async (n) => { log(n); return n; }); | |
* try { | |
* await pc.wait(); | |
* } catch (e) { | |
* log(e); | |
* } | |
* {/code} | |
*/ | |
export default class PromiseChain<State> { | |
private _promise: Promise<State> = Promise.resolve({} as State); | |
constructor(s: State) { | |
this.reset(s); | |
} | |
public reset(s: State = {} as State) { | |
this._promise = Promise.resolve(s); | |
} | |
public append(f: (s: State, ...args: any[]) => Promise<State>, ...args: any[]) { | |
this._promise = this._promise.then(async (s :State) => { | |
return await f(s, ...args); | |
}) | |
} | |
public async wait() { | |
try { await this._promise; } | |
catch (e) { throw e; } | |
finally { this.reset(); } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment