-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
79 lines (75 loc) · 2.07 KB
/
index.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* @module @promises/while-parallel
* @copyright © 2017 Yisrael Eliav <[email protected]> (https://github.com/yisraelx)
* @license MIT
*/
import { IOptionalPromise } from '@promises/interfaces';
import exec from '@promises/exec';
/**
* @function
* @example
*
* let index: number = 0;
*
* whileParallel(() => {
* console.log(`test ${index}`);
* return index++ < 3;
* }, () => {
* let thisIndex = index;
* return timeout((resolve) => {
* console.log(`iteratee ${thisIndex}`);
* resolve();
* }, 4 - index);
* }).then(() => {
* console.log('completed');
* });
*
* // => 'test 0'
* // => 'test 1'
* // => 'test 2'
* // => 'test 3'
* // => 'iteratee 3'
* // => 'iteratee 2'
* // => 'iteratee 1'
* // => 'completed'
*/
function whileParallel(test: () => IOptionalPromise<boolean>, iteratee: () => IOptionalPromise<any> = () => { }, limit: number = Infinity): Promise<void> {
limit--;
return new Promise((resolve, reject) => {
let count = 0;
let completed = 0;
let isStop = false;
let onReject = (error: any) => {
isStop = true;
reject(error);
};
let each = () => {
if (isStop) {
if (count === completed) {
resolve();
}
} else {
exec(test).then((isPass: boolean) => {
if (isPass && !isStop) {
count++;
exec(iteratee).then(() => {
completed++;
if (limit <= 0 || isStop) {
each();
}
}).catch(onReject);
if (limit > 0) {
limit--;
each();
}
} else {
isStop = true;
each();
}
}).catch(onReject);
}
};
each();
});
}
export default whileParallel;