-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsync.js
56 lines (41 loc) · 1.35 KB
/
Async.js
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
53
54
55
56
/* eslint-disable no-restricted-syntax, no-await-in-loop */
import { flattenArray, getArrayChunks } from 'utils/Array';
const sleep = (duration) => new Promise((resolve) => setTimeout(resolve, duration));
const sleepUntil = async (conditionFn, checkInterval = 200) => {
if (typeof conditionFn !== 'function') {
throw new Error('sleepUntil expects a function as first argument');
}
while (!conditionFn()) {
await sleep(checkInterval);
}
};
const sequentialPromiseMap = async (array, asyncFn, chunkSize) => {
const results = [];
let i = 0;
const chunked = chunkSize ? getArrayChunks(array, chunkSize) : array;
while (i < chunked.length) {
const res = await asyncFn(chunked[i]); // eslint-disable-line no-await-in-loop
results.push(res);
i += 1;
}
return chunkSize ? flattenArray(results) : results;
};
const sequentialPromiseFlatMap = async (array, asyncFn, chunkSize) => (
flattenArray(await sequentialPromiseMap(array, asyncFn, chunkSize))
);
const sequentialPromiseReduce = async (array, asyncFn) => {
const results = [];
let i = 0;
while (i < array.length) {
const res = await asyncFn(array[i], i, results); // eslint-disable-line no-await-in-loop
results.push(res);
i += 1;
}
return results;
};
export {
sequentialPromiseMap,
sequentialPromiseFlatMap,
sequentialPromiseReduce,
sleepUntil,
};