Skip to content

Commit 30e47d8

Browse files
committed
feat: add strict option to disallow then or catch following await or yield; fixes #294
1 parent c011a1a commit 30e47d8

File tree

3 files changed

+56
-2
lines changed

3 files changed

+56
-2
lines changed

__tests__/prefer-await-to-then.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ ruleTester.run('prefer-await-to-then', rule, {
1515
'async function hi() { await thing() }',
1616
'async function hi() { await thing().then() }',
1717
'async function hi() { await thing().catch() }',
18+
'function * hi() { yield thing().then() }',
1819
'a = async () => (await something())',
1920
`a = async () => {
2021
try { await something() } catch (error) { somethingElse() }
@@ -54,5 +55,32 @@ ruleTester.run('prefer-await-to-then', rule, {
5455
code: 'function foo() { hey.finally(x => {}) }',
5556
errors: [{ message }],
5657
},
58+
{
59+
code: 'async function hi() { await thing().then() }',
60+
errors: [{ message }],
61+
options: [
62+
{
63+
strict: true,
64+
},
65+
],
66+
},
67+
{
68+
code: 'async function hi() { await thing().catch() }',
69+
errors: [{ message }],
70+
options: [
71+
{
72+
strict: true,
73+
},
74+
],
75+
},
76+
{
77+
code: 'function * hi() { yield thing().then() }',
78+
errors: [{ message }],
79+
options: [
80+
{
81+
strict: true,
82+
},
83+
],
84+
},
5785
],
5886
})

docs/rules/prefer-await-to-then.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,18 @@ function exampleFour() {
4444
return myPromise.finally(cleanup)
4545
}
4646
```
47+
48+
## Options
49+
50+
### `strict`
51+
52+
Normally, this rule allows `then` or `catch` following an `await` (or `yield`)
53+
expression. Setting this option to `true` will err on such cases:
54+
55+
This will fail with the `strict` option:
56+
57+
```js
58+
async function hi() {
59+
await thing().then()
60+
}
61+
```

rules/prefer-await-to-then.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,16 @@ module.exports = {
1616
'Prefer `await` to `then()`/`catch()`/`finally()` for reading Promise values.',
1717
url: getDocsUrl('prefer-await-to-then'),
1818
},
19-
schema: [],
19+
schema: [
20+
{
21+
type: 'object',
22+
properties: {
23+
strict: {
24+
type: 'boolean',
25+
},
26+
},
27+
},
28+
],
2029
messages: {
2130
preferAwaitToCallback: 'Prefer await to then()/catch()/finally().',
2231
},
@@ -40,9 +49,11 @@ module.exports = {
4049
return getScope(context, node).block.type === 'Program'
4150
}
4251

52+
const { strict } = context.options[0] || {}
53+
4354
return {
4455
'CallExpression > MemberExpression.callee'(node) {
45-
if (isTopLevelScoped(node) || isInsideYieldOrAwait(node)) {
56+
if (isTopLevelScoped(node) || (!strict && isInsideYieldOrAwait(node))) {
4657
return
4758
}
4859

0 commit comments

Comments
 (0)