Skip to content

Commit d8b21c0

Browse files
committed
feat: add ts solution to lc problem: No.2721
No.2721.Execute Asynchronous Functions in Parallel
1 parent 7334f8b commit d8b21c0

File tree

3 files changed

+75
-2
lines changed

3 files changed

+75
-2
lines changed

solution/2700-2799/2721.Execute Asynchronous Functions in Parallel/README.md

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,31 @@ The single function was resolved at 200ms with a value of 5.
7878
<!-- 这里可写当前语言的特殊实现逻辑 -->
7979

8080
```ts
81-
81+
async function promiseAll<T>(functions: (() => Promise<T>)[]): Promise<T[]> {
82+
return new Promise<T[]>((resolve, reject) => {
83+
let cnt = 0;
84+
const ans = new Array(functions.length);
85+
for (let i = 0; i < functions.length; ++i) {
86+
const f = functions[i];
87+
f()
88+
.then(res => {
89+
ans[i] = res;
90+
cnt++;
91+
if (cnt === functions.length) {
92+
resolve(ans);
93+
}
94+
})
95+
.catch(err => {
96+
reject(err);
97+
});
98+
}
99+
});
100+
}
101+
102+
/**
103+
* const promise = promiseAll([() => new Promise(res => res(42))])
104+
* promise.then(console.log); // [42]
105+
*/
82106
```
83107

84108
<!-- tabs:end -->

solution/2700-2799/2721.Execute Asynchronous Functions in Parallel/README_EN.md

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,31 @@ The single function was resolved at 200ms with a value of 5.
7272
### **TypeScript**
7373

7474
```ts
75-
75+
async function promiseAll<T>(functions: (() => Promise<T>)[]): Promise<T[]> {
76+
return new Promise<T[]>((resolve, reject) => {
77+
let cnt = 0;
78+
const ans = new Array(functions.length);
79+
for (let i = 0; i < functions.length; ++i) {
80+
const f = functions[i];
81+
f()
82+
.then(res => {
83+
ans[i] = res;
84+
cnt++;
85+
if (cnt === functions.length) {
86+
resolve(ans);
87+
}
88+
})
89+
.catch(err => {
90+
reject(err);
91+
});
92+
}
93+
});
94+
}
95+
96+
/**
97+
* const promise = promiseAll([() => new Promise(res => res(42))])
98+
* promise.then(console.log); // [42]
99+
*/
76100
```
77101

78102
<!-- tabs:end -->
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
async function promiseAll<T>(functions: (() => Promise<T>)[]): Promise<T[]> {
2+
return new Promise<T[]>((resolve, reject) => {
3+
let cnt = 0;
4+
const ans = new Array(functions.length);
5+
for (let i = 0; i < functions.length; ++i) {
6+
const f = functions[i];
7+
f()
8+
.then(res => {
9+
ans[i] = res;
10+
cnt++;
11+
if (cnt === functions.length) {
12+
resolve(ans);
13+
}
14+
})
15+
.catch(err => {
16+
reject(err);
17+
});
18+
}
19+
});
20+
}
21+
22+
/**
23+
* const promise = promiseAll([() => new Promise(res => res(42))])
24+
* promise.then(console.log); // [42]
25+
*/

0 commit comments

Comments
 (0)