-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathpromise-all.ts
39 lines (32 loc) · 1.12 KB
/
promise-all.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { EOL } from "os"
const getMessageError = (state: PromiseRejectedResult) =>
state.reason.message ?? state.reason
const isRejected = (
state: PromiseSettledResult<unknown>
): state is PromiseRejectedResult => {
return state.status === "rejected"
}
const getValue = (state: PromiseFulfilledResult<unknown>) => state.value
/**
* Promise.allSettled with error handling, safe alternative to Promise.all
* @param promises
* @param aggregateErrors
*/
export async function promiseAll<T extends readonly unknown[] | []>(
promises: T,
{ aggregateErrors } = { aggregateErrors: false }
): Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }> {
const states = await Promise.allSettled(promises)
const rejected = (states as PromiseSettledResult<unknown>[]).filter(
isRejected
)
if (rejected.length) {
const aggregatedErrors = aggregateErrors
? rejected.map(getMessageError)
: [getMessageError(rejected[0])]
throw new Error(aggregatedErrors.join(EOL))
}
return (states as PromiseFulfilledResult<unknown>[]).map(
getValue
) as unknown as Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }>
}