Skip to content

Commit

Permalink
feat(prefer-await-to-then): ignore constructor scope unless with `s…
Browse files Browse the repository at this point in the history
…trict` option (#496)

Fixes #436

**What is the purpose of this pull request?**

- [x] Changes an existing rule

**What changes did you make? (Give an overview)**

Ignores constructor scope in `prefer-await-to-then` when reporting on
use of `then` (unless the `strict` option is enabled).

Co-authored-by: Yosuke Ota <otameshiyo23@gmail.com>
  • Loading branch information
brettz9 and ota-meshi authored Jul 24, 2024
1 parent d6e9de1 commit 7bffb7a
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
18 changes: 18 additions & 0 deletions __tests__/prefer-await-to-then.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ ruleTester.run('prefer-await-to-then', rule, {
`function isThenable(obj) {
return obj && typeof obj.then === 'function';
}`,
`class Foo {
constructor () {
doSomething.then(abc);
}
}`,
],

invalid: [
Expand Down Expand Up @@ -70,6 +75,19 @@ ruleTester.run('prefer-await-to-then', rule, {
},
],
},
{
code: `class Foo {
constructor () {
doSomething.then(abc);
}
}`,
errors: [{ message }],
options: [
{
strict: true,
},
],
},
{
code: 'async function hi() { await thing().catch() }',
errors: [{ message }],
Expand Down
4 changes: 2 additions & 2 deletions rules/lib/is-inside-callback.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const isInsidePromise = require('./is-inside-promise')

function isInsideCallback(node) {
const isCallExpression =
const isFunction =
node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression' ||
node.type === 'FunctionDeclaration' // this may be controversial
Expand All @@ -13,7 +13,7 @@ function isInsideCallback(node) {

const name = node.params && node.params[0] && node.params[0].name
const firstArgIsError = name === 'err' || name === 'error'
const isInACallback = isCallExpression && firstArgIsError
const isInACallback = isFunction && firstArgIsError
return isInACallback
}

Expand Down
10 changes: 10 additions & 0 deletions rules/prefer-await-to-then.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ module.exports = {
})
}

/** Returns true if node is inside a constructor */
function isInsideConstructor(node) {
return getAncestors(context, node).some((parent) => {
return (
parent.type === 'MethodDefinition' && parent.kind === 'constructor'
)
})
}

/**
* Returns true if node is created at the top-level scope.
* Await statements are not allowed at the top level,
Expand All @@ -57,6 +66,7 @@ module.exports = {
if (
isTopLevelScoped(node) ||
(!strict && isInsideYieldOrAwait(node)) ||
(!strict && isInsideConstructor(node)) ||
isMemberCallWithObjectName('cy', node.parent)
) {
return
Expand Down

0 comments on commit 7bffb7a

Please sign in to comment.