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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181 | 1×
1×
22×
22×
23×
15×
15×
15×
1×
14×
14×
14×
60×
57×
45×
45×
45×
45×
12×
12×
12×
12×
7×
7×
5×
3×
3×
14×
50×
8×
42×
42×
4×
42×
7×
35×
14×
14×
14×
61×
60×
60×
14×
47×
47×
1×
56×
56×
1×
6×
6×
3×
3×
1×
2×
1×
1×
1×
6×
6×
6×
3×
3×
1×
2×
1×
1×
| const DEFAULT_MAX = 5;
export interface Result<T> {
amountDone: number;
amountStarted: number;
amountResolved: number;
amountRejected: number;
rejectedIndexes: number[];
resolvedIndexes: number[];
taskResults: T[];
}
export type Task<T> = () => Promise<T>;
export type Tasks<T> = Array<Task<T>>;
export type nextTaskCheck = <T>(status: Result<T>, tasks: Tasks<T>) => Promise<boolean>;
/**
* Raw throttle function, which can return extra meta data.
* @param tasks array[] of functions
* @param maxInProgress integer with the max amount of tasks to be run in parallel
* @param failFast boolean if true, do fail-fast behaviour (see Promise.all() documentation)
* @param progressCallback function which can be used to see the progress
* @param nextCheck
* @returns {Promise}
*/
export function raw<T>(tasks: Tasks<T>,
maxInProgress = DEFAULT_MAX,
failFast = false,
progressCallback?: (result: Result<T>) => void,
nextCheck = defaultNextTaskCheck): Promise<Result<T>> {
return new Promise((resolve, reject) => {
const result: Result<T> = {
amountDone: 0,
amountStarted: 0,
amountResolved: 0,
amountRejected: 0,
rejectedIndexes: [],
resolvedIndexes: [],
taskResults: []
};
if (tasks.length === 0) {
return resolve(result);
}
let failedFast = false;
let amountQueued = 0;
const executeTask = (index: number) => {
if (typeof tasks[index] === 'function') {
tasks[index]()
.then((taskResult: T) => {
result.taskResults[index] = taskResult;
result.resolvedIndexes.push(index);
result.amountResolved++;
taskDone();
}, error => {
result.taskResults[index] = error;
result.rejectedIndexes.push(index);
result.amountRejected++;
if (failFast) {
failedFast = true;
return reject(result);
}
taskDone();
});
} else {
failedFast = true;
return reject(new Error('tasks[' + index + ']: ' + tasks[index] + ', is supposed to be of type function'));
}
};
const taskDone = () => {
//make sure no more tasks are spawned when we failedFast
if (failedFast) {
return;
}
result.amountDone++;
if (progressCallback) {
progressCallback(result);
}
if (result.amountDone === tasks.length) {
return resolve(result);
}
if (amountQueued < tasks.length) {
amountQueued++;
nextTask();
}
};
const nextTask = () => {
//check if we can execute the next task
nextCheck(result, tasks)
.then(canExecuteNextTask => {
Eif (canExecuteNextTask === true) {
//execute it
executeTask(result.amountStarted++);
}
}, reject);
};
//spawn the first X task
for (let i = 0; i < Math.min(maxInProgress, tasks.length); i++) {
amountQueued++;
nextTask();
}
});
}
/**
* Default checker which validates if a next task should begin.
* This can be overwritten to write own checks for example checking the amount
* of used ram and waiting till the ram is low enough for a next task.
*
* It should always resolve with a boolean, either `true` to start a next task
* or `false` to stop executing a new task.
*
* If this method rejects, the error will propagate to the caller
* @param status
* @param tasks
* @returns {Promise}
*/
const defaultNextTaskCheck: nextTaskCheck = <T>(status: Result<T>, tasks: Tasks<T>): Promise<boolean> => {
return new Promise((resolve, reject) => {
resolve(status.amountStarted < tasks.length);
});
};
/**
* Simply run all the promises after each other, so in synchronous manner
* @param tasks required array of tasks to be executed
* @param failFast optional boolean if we directly reject on a single error defaults to true
* @param progressCallback optional function to be run to get status updates
* @param nextCheck function which should return a promise, when resolved the next task will spawn
*/
export function sync<T>(tasks: Tasks<T>,
EfailFast = true,
progressCallback?: () => void,
EnextCheck = defaultNextTaskCheck): Promise<T[]> {
return new Promise((resolve, reject) => {
raw(tasks, 1, failFast, progressCallback, nextCheck)
.then((result: Result<T>) => {
resolve(result.taskResults);
}, (error: Error|Result<T>) => {
if (error instanceof Error) {
reject(error);
} else {
reject(error.taskResults[error.rejectedIndexes[0]]);
}
});
});
}
/**
* Exposes the same behaviour as Promise.All(), but throttled!
* @param tasks required array of tasks to be executed
* @param maxInProgress optional integer max amount of parallel tasks to be run defaults to 5
* @param failFast optional boolean if we directly reject on a single error defaults to true
* @param progressCallback optional function to be run to get status updates
* @param nextCheck function which should return a promise, when resolved the next task will spawn
*/
export function all<T>(tasks: Tasks<T>,
EmaxInProgress = DEFAULT_MAX,
EfailFast = true,
progressCallback?: () => void,
EnextCheck = defaultNextTaskCheck): Promise<T[]> {
return new Promise((resolve, reject) => {
raw(tasks, maxInProgress, failFast, progressCallback, nextCheck)
.then((result: Result<T>) => {
resolve(result.taskResults);
}, (error: Error|Result<T>) => {
if (error instanceof Error) {
reject(error);
} else {
reject(error.taskResults[error.rejectedIndexes[0]]);
}
});
});
}
|