-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecuteFunctionsInparallel.js
More file actions
53 lines (41 loc) · 1.49 KB
/
executeFunctionsInparallel.js
File metadata and controls
53 lines (41 loc) · 1.49 KB
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
function executeAsyncFunctionsInParallel(functions) {
return new Promise((resolve, reject) => {
const results = [];
let completedCount = 0;
let hasRejected = false;
// Function to handle the resolution of each promise
function handleResolve(index, result) {
results[index] = result;
completedCount++;
// If all promises have resolved, resolve the main promise with the results
if (completedCount === functions.length) {
resolve(results);
}
}
// Function to handle the rejection of any promise
function handleReject(reason) {
if (!hasRejected) {
hasRejected = true;
reject(reason);
}
}
// Execute each asynchronous function and handle its promise
for (let i = 0; i < functions.length; i++) {
const index = i;
const promise = functions[i]();
promise.then((result) => {
handleResolve(index, result);
}).catch((error) => {
handleReject(error);
});
}
});
}
// var promiseAll = function(functions) {
// const promises = [];
// for (let i = 0; i < functions.length; i++) {
// promises.push(Promise.resolve(functions[i]()));
// }
// return Promise.all(promises);
// };
// var promiseAll = async function(functions) { return Promise.all(functions.map((f) => f())); };