Skip to content

Instantly share code, notes, and snippets.

@TheCrafter
Last active October 23, 2019 13:18
Show Gist options
  • Save TheCrafter/eb32496eaa050e0fa616705789c4df6c to your computer and use it in GitHub Desktop.
Save TheCrafter/eb32496eaa050e0fa616705789c4df6c to your computer and use it in GitHub Desktop.
A wrapper around promises that allows for easy chaining them together.
/**
* 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