@@ -23,6 +23,25 @@ while (promise) {
23
23
}
24
24
```
25
25
26
+ Examples of ** correct** code with ` checksConditionals: true ` :
27
+
28
+ ``` ts
29
+ const promise = Promise .resolve (' value' );
30
+
31
+ // Always `await` the Promise in a conditional
32
+ if (await promise ) {
33
+ // Do something
34
+ }
35
+
36
+ const val = (await promise ) ? 123 : 456 ;
37
+
38
+ while (await promise ) {
39
+ // Do something
40
+ }
41
+ ```
42
+
43
+ ---
44
+
26
45
Examples of ** incorrect** code for this rule with ` checksVoidReturn: true ` :
27
46
28
47
``` ts
@@ -37,37 +56,51 @@ new Promise(async (resolve, reject) => {
37
56
38
57
const eventEmitter = new EventEmitter ();
39
58
eventEmitter .on (' some-event' , async () => {
59
+ synchronousCall ();
40
60
await doSomething ();
61
+ otherSynchronousCall ();
41
62
});
42
63
```
43
64
44
- Examples of ** correct** code for this rule :
65
+ Examples of ** correct** code with ` checksVoidReturn: true ` :
45
66
46
67
``` ts
47
- const promise = Promise .resolve (' value' );
48
-
49
- if (await promise ) {
50
- // Do something
51
- }
52
-
53
- const val = (await promise ) ? 123 : 456 ;
54
-
55
- while (await promise ) {
56
- // Do something
57
- }
58
-
68
+ // for-of puts `await` in outer context
59
69
for (const value of [1 , 2 , 3 ]) {
60
70
await doSomething (value );
61
71
}
62
72
73
+ // If outer context is not `async`, handle error explicitly
74
+ Promise .all (
75
+ [1 , 2 , 3 ].map (async value => {
76
+ await doSomething (value );
77
+ }),
78
+ ).catch (handleError );
79
+
80
+ // Use an async IIFE wrapper
63
81
new Promise ((resolve , reject ) => {
64
- // Do something
65
- resolve ();
82
+ // combine with `void` keyword to tell `no-floating-promises` rule to ignore unhandled rejection
83
+ void (async () => {
84
+ await doSomething ();
85
+ resolve ();
86
+ })();
66
87
});
67
88
89
+ // Name the async wrapper to call it later
68
90
const eventEmitter = new EventEmitter ();
69
91
eventEmitter .on (' some-event' , () => {
70
- doSomething ();
92
+ const handler = async () => {
93
+ await doSomething ();
94
+ otherSynchronousCall ();
95
+ };
96
+
97
+ try {
98
+ synchronousCall ();
99
+ } catch (err ) {
100
+ handleSpecificError (err );
101
+ }
102
+
103
+ handler ().catch (handleError );
71
104
});
72
105
```
73
106
0 commit comments