-
Notifications
You must be signed in to change notification settings - Fork 4
/
settle-all.ts
52 lines (50 loc) · 1.51 KB
/
settle-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
40
41
42
43
44
45
46
47
48
49
50
51
52
export interface SettledPromises<T, V> {
errors: V[];
results: T[];
}
/**
* 处理多个promise的时候,返回promise数组的成功失败结果,索引为promise数组下标
* 并行Promise.all执行
* @param promises
* @param errFn
* @category Promise
*/
async function settleAll<T, V>(
promises: readonly Promise<T>[],
errFn?: (err: any, ind: number) => Promise<V>,
): Promise<SettledPromises<T, V>>;
async function settleAll<T, V>(
promises: readonly Promise<T>[],
errFn?: (err: any) => Promise<V>,
): Promise<SettledPromises<T, V>>;
async function settleAll<T, V>(
promises: readonly Promise<T>[],
errFn?: (err: any, ind: number) => V,
): Promise<SettledPromises<T, V>>;
async function settleAll<T, V>(
promises: readonly Promise<T>[],
errFn?: (err: any) => V,
): Promise<SettledPromises<T, V>>;
async function settleAll<T, V>(
promises: readonly Promise<T>[],
errFn: (err: any, ind: number) => V = (err) => err,
): Promise<SettledPromises<T, V>> {
const intermediateResults = await Promise.all(
(promises || []).map(async (p, i) => {
try {
return { result: await p };
} catch (err) {
return { error: await errFn(err, i) };
}
}),
);
const settledPromises: SettledPromises<T, V> = { results: [], errors: [] };
intermediateResults.reduce((acc, res) => {
const { result, error } = res;
if (error) acc.errors.push(error);
if (result) acc.results.push(result);
return acc;
}, settledPromises);
return settledPromises;
}
export default settleAll;