Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ignore top-level awaits in prefer-await-to-then #126

Merged
merged 1 commit into from May 24, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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