/** * 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(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 { private _promise: Promise = 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, ...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(); } } }