Last active
May 17, 2023 12:07
-
-
Save everdimension/44201ccf5cad45cb27ef373d77471b6b to your computer and use it in GitHub Desktop.
Implementation of Promise.any using Promise.all
This file contains 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
/** | |
* As of writing, Promise.any is Stage 4 (Finished) | |
* This code is just a fun reminder of how Promise.any can be implemented using Promise.all | |
* Proposal: https://github.com/tc39/proposal-promise-any | |
*/ | |
class AggregateErrorFallback extends Error { | |
errors: Array<Error>; | |
constructor(message: string, errors: Array<Error>) { | |
super(message); | |
this.name = 'AggregateError'; | |
this.errors = errors; | |
} | |
} | |
function promiseAny<T>(values: Array<PromiseLike<T>>): Promise<Awaited<T>> { | |
const identity = <T>(x: T) => x; | |
const errors: Array<Error> = []; | |
return Promise.all( | |
values.map((promise) => | |
promise.then( | |
(result) => { | |
throw result; | |
}, | |
(error) => { | |
errors.push(error); | |
return error; | |
} | |
) | |
) | |
).then(() => { | |
/** | |
* Promise.any implementation throws AggregateError: | |
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError | |
*/ | |
const message = 'All promises were rejected'; | |
throw new AggregateErrorFallback(message, errors); | |
}, identity); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment