Skip to content

Commit ee54aee

Browse files
committed
Add solution #2721
1 parent 552cdde commit ee54aee

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,7 @@
407407
2677|[Chunk Array](./2677-chunk-array.js)|Easy|
408408
2695|[Array Wrapper](./2695-array-wrapper.js)|Easy|
409409
2703|[Return Length of Arguments Passed](./2703-return-length-of-arguments-passed.js)|Easy|
410+
2721|[Execute Asynchronous Functions in Parallel](./2721-execute-asynchronous-functions-in-parallel.js)|Medium|
410411
3042|[Count Prefix and Suffix Pairs I](./3042-count-prefix-and-suffix-pairs-i.js)|Easy|
411412
3110|[Score of a String](./3110-score-of-a-string.js)|Easy|
412413
3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy|
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 2721. Execute Asynchronous Functions in Parallel
3+
* https://leetcode.com/problems/execute-asynchronous-functions-in-parallel/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of asynchronous functions functions, return a new promise promise.
7+
* Each function in the array accepts no arguments and returns a promise. All the
8+
* promises should be executed in parallel.
9+
*
10+
* promise resolves:
11+
* - When all the promises returned from functions were resolved successfully in
12+
* parallel. The resolved value of promise should be an array of all the resolved
13+
* values of promises in the same order as they were in the functions. The promise
14+
* should resolve when all the asynchronous functions in the array have completed
15+
* execution in parallel.
16+
*
17+
* promise rejects:
18+
* When any of the promises returned from functions were rejected. promise should
19+
* also reject with the reason of the first rejection.
20+
*
21+
* Please solve it without using the built-in Promise.all function.
22+
*/
23+
24+
/**
25+
* @param {Array<Function>} functions
26+
* @return {Promise<any>}
27+
*/
28+
var promiseAll = function(functions) {
29+
return new Promise((resolve, reject) => {
30+
const promises = new Array(functions.length);
31+
let count = 0;
32+
functions.forEach((fn, i) => {
33+
fn().then(result => {
34+
promises[i] = result;
35+
if (++count === promises.length) {
36+
resolve(promises);
37+
}
38+
}).catch(reject);
39+
});
40+
});
41+
};

0 commit comments

Comments
 (0)