Skip to content

Commit

Permalink
feat: add strict option to disallow then or catch following `aw…
Browse files Browse the repository at this point in the history
…ait` or `yield` (eslint-community#494)
  • Loading branch information
brettz9 authored Jul 21, 2024
1 parent f368c5a commit fa482cc
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 2 deletions.
38 changes: 38 additions & 0 deletions __tests__/prefer-await-to-then.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ ruleTester.run('prefer-await-to-then', rule, {
'async function hi() { await thing() }',
'async function hi() { await thing().then() }',
'async function hi() { await thing().catch() }',
'async function hi() { await thing().finally() }',
'function * hi() { yield thing().then() }',
'a = async () => (await something())',
`a = async () => {
try { await something() } catch (error) { somethingElse() }
Expand Down Expand Up @@ -54,5 +56,41 @@ ruleTester.run('prefer-await-to-then', rule, {
code: 'function foo() { hey.finally(x => {}) }',
errors: [{ message }],
},
{
code: 'async function hi() { await thing().then() }',
errors: [{ message }],
options: [
{
strict: true,
},
],
},
{
code: 'async function hi() { await thing().catch() }',
errors: [{ message }],
options: [
{
strict: true,
},
],
},
{
code: 'async function hi() { await thing().finally() }',
errors: [{ message }],
options: [
{
strict: true,
},
],
},
{
code: 'function * hi() { yield thing().then() }',
errors: [{ message }],
options: [
{
strict: true,
},
],
},
],
})
15 changes: 15 additions & 0 deletions docs/rules/prefer-await-to-then.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,18 @@ function exampleFour() {
return myPromise.finally(cleanup)
}
```

## Options

### `strict`

Normally, this rule allows `then` or `catch` following an `await` (or `yield`)
expression. Setting this option to `true` will err on such cases:

This will fail with the `strict` option:

```js
async function hi() {
await thing().then()
}
```
15 changes: 13 additions & 2 deletions rules/prefer-await-to-then.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,16 @@ module.exports = {
'Prefer `await` to `then()`/`catch()`/`finally()` for reading Promise values.',
url: getDocsUrl('prefer-await-to-then'),
},
schema: [],
schema: [
{
type: 'object',
properties: {
strict: {
type: 'boolean',
},
},
},
],
messages: {
preferAwaitToCallback: 'Prefer await to then()/catch()/finally().',
},
Expand All @@ -40,9 +49,11 @@ module.exports = {
return getScope(context, node).block.type === 'Program'
}

const { strict } = context.options[0] || {}

return {
'CallExpression > MemberExpression.callee'(node) {
if (isTopLevelScoped(node) || isInsideYieldOrAwait(node)) {
if (isTopLevelScoped(node) || (!strict && isInsideYieldOrAwait(node))) {
return
}

Expand Down

0 comments on commit fa482cc

Please sign in to comment.