Skip to content

Commit 4a3d5b8

Browse files
authored
fix: ignore top-level awaits in prefer-await-to-then (#126)
Resolves #122
1 parent 0b231da commit 4a3d5b8

File tree

2 files changed

+25
-13
lines changed

2 files changed

+25
-13
lines changed

__tests__/prefer-await-to-then.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,22 @@ ruleTester.run('prefer-await-to-then', rule, {
1414
valid: [
1515
'async function hi() { await thing() }',
1616
'async function hi() { await thing().then() }',
17-
'async function hi() { await thing().catch() }'
17+
'async function hi() { await thing().catch() }',
18+
'a = async () => (await something())',
19+
'something().then(async () => await somethingElse())'
1820
],
1921

2022
invalid: [
2123
{
22-
code: 'hey.then(x => {})',
24+
code: 'function foo() { hey.then(x => {}) }',
2325
errors: [{ message }]
2426
},
2527
{
26-
code: 'hey.then(function() { }).then()',
28+
code: 'function foo() { hey.then(function() { }).then() }',
2729
errors: [{ message }, { message }]
2830
},
2931
{
30-
code: 'hey.then(function() { }).then(x).catch()',
32+
code: 'function foo() { hey.then(function() { }).then(x).catch() }',
3133
errors: [{ message }, { message }]
3234
},
3335
{

rules/prefer-await-to-then.js

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,27 @@ module.exports = {
1414
}
1515
},
1616
create: function(context) {
17+
/** Returns true if node is inside yield or await expression. */
18+
function isInsideYieldOrAwait() {
19+
return context.getAncestors().some(parent => {
20+
return (
21+
parent.type === 'AwaitExpression' || parent.type === 'YieldExpression'
22+
)
23+
})
24+
}
25+
26+
/**
27+
* Returns true if node is created at the top-level scope.
28+
* Await statements are not allowed at the top level,
29+
* only within function declarations.
30+
*/
31+
function isTopLevelScoped() {
32+
return context.getScope().block.type === 'Program'
33+
}
34+
1735
return {
1836
MemberExpression: function(node) {
19-
// you can then() if you are inside of a yield or await
20-
if (
21-
context.getAncestors().some(function(parent) {
22-
return (
23-
parent.type === 'AwaitExpression' ||
24-
parent.type === 'YieldExpression'
25-
)
26-
})
27-
) {
37+
if (isTopLevelScoped() || isInsideYieldOrAwait()) {
2838
return
2939
}
3040

0 commit comments

Comments
 (0)