Skip to content

Commit 5a666d6

Browse files
committed
feat(prefer-await-to-then): ignore constructor scope unless with strict option; fixes eslint-community#436
1 parent fa482cc commit 5a666d6

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

__tests__/prefer-await-to-then.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@ ruleTester.run('prefer-await-to-then', rule, {
2929
`function isThenable(obj) {
3030
return obj && typeof obj.then === 'function';
3131
}`,
32+
`class Foo {
33+
constructor () {
34+
doSomething.then(abc);
35+
}
36+
}`,
3237
],
3338

3439
invalid: [
@@ -65,6 +70,19 @@ ruleTester.run('prefer-await-to-then', rule, {
6570
},
6671
],
6772
},
73+
{
74+
code: `class Foo {
75+
constructor () {
76+
doSomething.then(abc);
77+
}
78+
}`,
79+
errors: [{ message }],
80+
options: [
81+
{
82+
strict: true,
83+
},
84+
],
85+
},
6886
{
6987
code: 'async function hi() { await thing().catch() }',
7088
errors: [{ message }],

rules/lib/is-inside-callback.js

Lines changed: 2 additions & 2 deletions
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

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,15 @@ module.exports = {
4040
})
4141
}
4242

43+
/** Returns true if node is inside a constructor */
44+
function isInsideConstructor(node) {
45+
return getAncestors(context, node).some((parent) => {
46+
return (
47+
parent.type === 'MethodDefinition' && parent.kind === 'constructor'
48+
)
49+
})
50+
}
51+
4352
/**
4453
* Returns true if node is created at the top-level scope.
4554
* Await statements are not allowed at the top level,
@@ -53,7 +62,11 @@ module.exports = {
5362

5463
return {
5564
'CallExpression > MemberExpression.callee'(node) {
56-
if (isTopLevelScoped(node) || (!strict && isInsideYieldOrAwait(node))) {
65+
if (
66+
isTopLevelScoped(node) ||
67+
(!strict && isInsideYieldOrAwait(node)) ||
68+
(!strict && isInsideConstructor(node))
69+
) {
5770
return
5871
}
5972

0 commit comments

Comments
 (0)