Skip to content

Instantly share code, notes, and snippets.

@everdimension
Last active May 17, 2023 12:07
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 everdimension/44201ccf5cad45cb27ef373d77471b6b to your computer and use it in GitHub Desktop.
Save everdimension/44201ccf5cad45cb27ef373d77471b6b to your computer and use it in GitHub Desktop.
Implementation of Promise.any using Promise.all
/**
* 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