-
Notifications
You must be signed in to change notification settings - Fork 1
/
asyncParallel.js
42 lines (38 loc) · 905 Bytes
/
asyncParallel.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
function createAsyncTask() {
const value = Math.floor(Math.random() * 9);
return new Promise((resolve, reject) => {
setTimeout(() => {
if (value < 5) {
reject(value)
} else {
resolve(value);
}
}, value * 1000);
})
}
const asyncTasksList = [
createAsyncTask();
createAsyncTask();
createAsyncTask();
createAsyncTask();
createAsyncTask();
]
function executeAsyncTasksInParallel(asyncTasks, callback) {
const results = [];
const errors = [];
let completed = 0;
asyncTasks.forEach(asyncTask => {
asyncTask
.then(res => results.push(res));
.catch(err => errors.push(err));
.finally(() => {
completed++;
if (completed >= asyncTasks.length) {
callback(results, errors);
}
})
})
}
executeAsyncTasksInParallel(asyncTasksList, (data, errors) => {
console.log(data, errors);
})