refactor: Simplify promiseSome.

This commit is contained in:
Ruben Verborgh 2021-11-17 23:28:57 +00:00
parent c13456c225
commit 5a01f09f81

View File

@ -1,7 +1,7 @@
import { createAggregateError } from './errors/HttpErrorUtil'; import { createAggregateError } from './errors/HttpErrorUtil';
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
const infinitePromise = new Promise<boolean>((): void => {}); function noop(): void {}
/** /**
* A function that simulates the Array.some behaviour but on an array of Promises. * A function that simulates the Array.some behaviour but on an array of Promises.
@ -16,19 +16,15 @@ const infinitePromise = new Promise<boolean>((): void => {});
* 2. throwing an error should be logically equivalent to returning false. * 2. throwing an error should be logically equivalent to returning false.
*/ */
export async function promiseSome(predicates: Promise<boolean>[]): Promise<boolean> { export async function promiseSome(predicates: Promise<boolean>[]): Promise<boolean> {
// These promises will only finish when their predicate returns true return new Promise((resolve): void => {
const infinitePredicates = predicates.map(async(predicate): Promise<boolean> => predicate.then( function resolveIfTrue(value: boolean): void {
async(value): Promise<boolean> => value ? true : infinitePromise, if (value) {
async(): Promise<boolean> => infinitePromise, resolve(true);
)); }
}
// Returns after all predicates are resolved Promise.all(predicates.map((predicate): Promise<void> => predicate.then(resolveIfTrue, noop)))
const finalPromise = Promise.allSettled(predicates).then((results): boolean => .then((): void => resolve(false), noop);
results.some((result): boolean => result.status === 'fulfilled' && result.value)); });
// Either one of the infinitePredicates will return true,
// or finalPromise will return the result if none of them did or finalPromise was faster
return Promise.race([ ...infinitePredicates, finalPromise ]);
} }
/** /**