File tree Expand file tree Collapse file tree 3 files changed +75
-2
lines changed
solution/2700-2799/2721.Execute Asynchronous Functions in Parallel Expand file tree Collapse file tree 3 files changed +75
-2
lines changed Original file line number Diff line number Diff line change @@ -78,7 +78,31 @@ The single function was resolved at 200ms with a value of 5.
78
78
<!-- 这里可写当前语言的特殊实现逻辑 -->
79
79
80
80
``` 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
+ */
82
106
```
83
107
84
108
<!-- tabs:end -->
Original file line number Diff line number Diff line change @@ -72,7 +72,31 @@ The single function was resolved at 200ms with a value of 5.
72
72
### ** TypeScript**
73
73
74
74
``` 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
+ */
76
100
```
77
101
78
102
<!-- tabs:end -->
Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments