Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Last active September 4, 2020 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabemeola/ccc1a2d0b3a62b45022004b756dab14a to your computer and use it in GitHub Desktop.
Save gabemeola/ccc1a2d0b3a62b45022004b756dab14a to your computer and use it in GitHub Desktop.
Allows all promises to be awaited while capturing values
function noop() {}
type CatchCallback<T> = Parameters<Promise<T>['catch']>[0];
class PromiseChain<T> {
#chain: Promise<any> = Promise.resolve();
#values: Array<T> = [];
add(promise: Promise<T | void | undefined>, promiseCatch: CatchCallback<T> = noop) {
this.#chain = this.#chain
.then(() => promise)
.then((value) => {
if (typeof value !== 'undefined') {
this.#values.push(value);
}
})
.catch(promiseCatch);
}
values() {
return this.#chain.then(() => this.#values);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment