Skip to content

Commit

Permalink
fix: ignore top-level awaits in prefer-await-to-then (#126)
Browse files Browse the repository at this point in the history
Resolves #122
  • Loading branch information
macklinu committed May 24, 2018
1 parent 0b231da commit 4a3d5b8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
10 changes: 6 additions & 4 deletions __tests__/prefer-await-to-then.js
Expand Up @@ -14,20 +14,22 @@ ruleTester.run('prefer-await-to-then', rule, {
valid: [
'async function hi() { await thing() }',
'async function hi() { await thing().then() }',
'async function hi() { await thing().catch() }'
'async function hi() { await thing().catch() }',
'a = async () => (await something())',
'something().then(async () => await somethingElse())'
],

invalid: [
{
code: 'hey.then(x => {})',
code: 'function foo() { hey.then(x => {}) }',
errors: [{ message }]
},
{
code: 'hey.then(function() { }).then()',
code: 'function foo() { hey.then(function() { }).then() }',
errors: [{ message }, { message }]
},
{
code: 'hey.then(function() { }).then(x).catch()',
code: 'function foo() { hey.then(function() { }).then(x).catch() }',
errors: [{ message }, { message }]
},
{
Expand Down
28 changes: 19 additions & 9 deletions rules/prefer-await-to-then.js
Expand Up @@ -14,17 +14,27 @@ module.exports = {
}
},
create: function(context) {
/** Returns true if node is inside yield or await expression. */
function isInsideYieldOrAwait() {
return context.getAncestors().some(parent => {
return (
parent.type === 'AwaitExpression' || parent.type === 'YieldExpression'
)
})
}

/**
* Returns true if node is created at the top-level scope.
* Await statements are not allowed at the top level,
* only within function declarations.
*/
function isTopLevelScoped() {
return context.getScope().block.type === 'Program'
}

return {
MemberExpression: function(node) {
// you can then() if you are inside of a yield or await
if (
context.getAncestors().some(function(parent) {
return (
parent.type === 'AwaitExpression' ||
parent.type === 'YieldExpression'
)
})
) {
if (isTopLevelScoped() || isInsideYieldOrAwait()) {
return
}

Expand Down

0 comments on commit 4a3d5b8

Please sign in to comment.