diff --git a/__tests__/prefer-await-to-then.js b/__tests__/prefer-await-to-then.js index a0982f7b..4d88a0f8 100644 --- a/__tests__/prefer-await-to-then.js +++ b/__tests__/prefer-await-to-then.js @@ -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 }] }, { diff --git a/rules/prefer-await-to-then.js b/rules/prefer-await-to-then.js index 99db9153..556ce7f6 100644 --- a/rules/prefer-await-to-then.js +++ b/rules/prefer-await-to-then.js @@ -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 }