forked from 0xPolygon/fx-portal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap_promise.ts
35 lines (29 loc) · 915 Bytes
/
map_promise.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
import { promiseResolve } from "./promise_resolve";
export interface IMapPromiseOption {
concurrency: number;
}
const runPromises = (promises: Array<Promise<any>>, converter: Function) => {
const maps = promises.map((val, index) => {
return converter(val, index);
});
return Promise.all(maps);
};
export function mapPromise(
values: any[],
converter: Function,
option: IMapPromiseOption = {} as any
) {
const valuesLength = values.length;
const concurrency = option.concurrency || valuesLength;
let result: any = [];
const limitPromiseRun: () => Promise<any> = () => {
const promises = values.splice(0, concurrency);
return runPromises(promises, converter).then((promiseResult) => {
result = result.concat(promiseResult);
return valuesLength > result.length
? limitPromiseRun()
: promiseResolve(result);
});
};
return limitPromiseRun();
}