Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion __tests__/prefer-await-to-callbacks.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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