-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecute Asynchronous Functions in Parallel.js
More file actions
53 lines (41 loc) · 1.91 KB
/
Execute Asynchronous Functions in Parallel.js
File metadata and controls
53 lines (41 loc) · 1.91 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
// Given an array of asynchronous functions functions, return a new promise promise. Each function in the array accepts no arguments and returns a promise. All the promises should be executed in parallel.
// promise resolves:
// When all the promises returned from functions were resolved successfully in parallel. The resolved value of promise should be an array of all the resolved values of promises in the same order as they were in the functions. The promise should resolve when all the asynchronous functions in the array have completed execution in parallel.
// promise rejects:
// When any of the promises returned from functions were rejected. promise should also reject with the reason of the first rejection.
// Please solve it without using the built-in Promise.all function.
// Example 1:
// Input: functions = [
// () => new Promise(resolve => setTimeout(() => resolve(5), 200))
// ]
// Output: {"t": 200, "resolved": [5]}
// Explanation:
// promiseAll(functions).then(console.log); // [5]
// The single function was resolved at 200ms with a value of 5.
/**
* @param {Array<Function>} functions
* @return {Promise<any>}
*/
var promiseAll = function(functions) {
return new Promise((resolve, reject) => {
const results = [];
let completed = 0;
functions.forEach((fn, index) => {
fn()
.then((result) => {
results[index] = result; // Store the result in the same order
completed += 1;
if (completed === functions.length) {
resolve(results); // Resolve when all promises are fulfilled
}
})
.catch((error) => {
reject(error); // Reject if any promise fails
});
});
});
};
/**
* const promise = promiseAll([() => new Promise(res => res(42))])
* promise.then(console.log); // [42]
*/