-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncParallel.js
48 lines (41 loc) · 917 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
43
44
45
46
47
48
// Input:
// executeParallel([asyncTask(3), asyncTask(1), asyncTask(2)], (result) => {
// console.log(result);
// });
// Output:
// // output in the order of execution
// [2, 1, 3]
// Input:
const taskList = [
createAsyncTask(),
createAsyncTask(),
createAsyncTask(),
createAsyncTask(),
createAsyncTask(),
createAsyncTask(),
];
function executeParallel(asyncArray, callBack) {
let results = [];
asyncArray.forEach((item, index) => {
item((value) => {
results.push(value);
if (results.length >= asyncArray.length) {
callBack(results);
}
});
});
}
function createAsyncTask() {
const value = Math.floor(Math.random() * 10);
return function (callback) {
setTimeout(() => {
callback(value);
}, value * 1000);
};
}
executeParallel(taskList, (result) => {
console.log(result);
});
// Output:
// "results" // [object Array] (6)
// [1,6,7,7,9,9]