Last active
September 4, 2020 17:27
-
-
Save gabemeola/ccc1a2d0b3a62b45022004b756dab14a to your computer and use it in GitHub Desktop.
Allows all promises to be awaited while capturing values
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
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