Skip to content

Commit 7bffb7a

Browse files
brettz9ota-meshi
andauthoredJul 24, 2024··
feat(prefer-await-to-then): ignore constructor scope unless with strict 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>
1 parent d6e9de1 commit 7bffb7a

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed
 

‎__tests__/prefer-await-to-then.js

+18
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ ruleTester.run('prefer-await-to-then', rule, {
3434
`function isThenable(obj) {
3535
return obj && typeof obj.then === 'function';
3636
}`,
37+
`class Foo {
38+
constructor () {
39+
doSomething.then(abc);
40+
}
41+
}`,
3742
],
3843

3944
invalid: [
@@ -70,6 +75,19 @@ ruleTester.run('prefer-await-to-then', rule, {
7075
},
7176
],
7277
},
78+
{
79+
code: `class Foo {
80+
constructor () {
81+
doSomething.then(abc);
82+
}
83+
}`,
84+
errors: [{ message }],
85+
options: [
86+
{
87+
strict: true,
88+
},
89+
],
90+
},
7391
{
7492
code: 'async function hi() { await thing().catch() }',
7593
errors: [{ message }],

‎rules/lib/is-inside-callback.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
const isInsidePromise = require('./is-inside-promise')
44

55
function isInsideCallback(node) {
6-
const isCallExpression =
6+
const isFunction =
77
node.type === 'FunctionExpression' ||
88
node.type === 'ArrowFunctionExpression' ||
99
node.type === 'FunctionDeclaration' // this may be controversial
@@ -13,7 +13,7 @@ function isInsideCallback(node) {
1313

1414
const name = node.params && node.params[0] && node.params[0].name
1515
const firstArgIsError = name === 'err' || name === 'error'
16-
const isInACallback = isCallExpression && firstArgIsError
16+
const isInACallback = isFunction && firstArgIsError
1717
return isInACallback
1818
}
1919

‎rules/prefer-await-to-then.js

+10
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,15 @@ module.exports = {
4141
})
4242
}
4343

44+
/** Returns true if node is inside a constructor */
45+
function isInsideConstructor(node) {
46+
return getAncestors(context, node).some((parent) => {
47+
return (
48+
parent.type === 'MethodDefinition' && parent.kind === 'constructor'
49+
)
50+
})
51+
}
52+
4453
/**
4554
* Returns true if node is created at the top-level scope.
4655
* Await statements are not allowed at the top level,
@@ -57,6 +66,7 @@ module.exports = {
5766
if (
5867
isTopLevelScoped(node) ||
5968
(!strict && isInsideYieldOrAwait(node)) ||
69+
(!strict && isInsideConstructor(node)) ||
6070
isMemberCallWithObjectName('cy', node.parent)
6171
) {
6272
return

0 commit comments

Comments
 (0)
Please sign in to comment.