Skip to content

Commit

Permalink
fix: ignore event listener callbacks in prefer-await-to-callbacks (#117)
Browse files Browse the repository at this point in the history
Resolves #116 

* test: add failing test for #116

* fix(rule): ignore reporting on event listener callbacks
  • Loading branch information
macklinu committed May 24, 2018
1 parent 4a3d5b8 commit 4ebd2c6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 19 deletions.
4 changes: 3 additions & 1 deletion __tests__/prefer-await-to-callbacks.js
Expand Up @@ -14,7 +14,9 @@ ruleTester.run('prefer-await-to-callbacks', rule, {
valid: [
'async function hi() { await thing().catch(err => console.log(err)) }',
'async function hi() { await thing().then() }',
'async function hi() { await thing().catch() }'
'async function hi() { await thing().catch() }',
'dbConn.on("error", err => { console.error(err) })',
'dbConn.once("error", err => { console.error(err) })'
],

invalid: [
Expand Down
35 changes: 17 additions & 18 deletions rules/prefer-await-to-callbacks.js
@@ -1,8 +1,3 @@
/**
* Rule: prefer-await-to-callbacks
* Discourage using then() and instead use async/await.
*/

'use strict'

const getDocsUrl = require('./lib/get-docs-url')
Expand All @@ -15,40 +10,44 @@ module.exports = {
url: getDocsUrl('prefer-await-to-callbacks')
}
},
create: function(context) {
create(context) {
function checkLastParamsForCallback(node) {
const len = node.params.length - 1
const lastParam = node.params[len]
if (
lastParam &&
(lastParam.name === 'callback' || lastParam.name === 'cb')
) {
const lastParam = node.params[node.params.length - 1] || {}
if (lastParam.name === 'callback' || lastParam.name === 'cb') {
context.report({ node: lastParam, message: errorMessage })
}
}
function isInsideYieldOrAwait() {
return context.getAncestors().some(function(parent) {
return context.getAncestors().some(parent => {
return (
parent.type === 'AwaitExpression' || parent.type === 'YieldExpression'
)
})
}
return {
CallExpression: function(node) {
// callbacks aren't allowed
CallExpression(node) {
// Callbacks aren't allowed.
if (node.callee.name === 'cb' || node.callee.name === 'callback') {
context.report({ node, message: errorMessage })
return
}

// thennables aren't allowed either
// Then-ables aren't allowed either.
const args = node.arguments
const num = args.length - 1
const arg = num > -1 && node.arguments && node.arguments[num]
const lastArgIndex = args.length - 1
const arg = lastArgIndex > -1 && node.arguments[lastArgIndex]
if (
(arg && arg.type === 'FunctionExpression') ||
arg.type === 'ArrowFunctionExpression'
) {
// Ignore event listener callbacks.
if (
node.callee.property &&
(node.callee.property.name === 'on' ||
node.callee.property.name === 'once')
) {
return
}
if (arg.params && arg.params[0] && arg.params[0].name === 'err') {
if (!isInsideYieldOrAwait()) {
context.report({ node: arg, message: errorMessage })
Expand Down

0 comments on commit 4ebd2c6

Please sign in to comment.