1- /**
2- * Rule: prefer-await-to-callbacks
3- * Discourage using then() and instead use async/await.
4- */
5-
61'use strict'
72
83const getDocsUrl = require ( './lib/get-docs-url' )
@@ -15,40 +10,44 @@ module.exports = {
1510 url : getDocsUrl ( 'prefer-await-to-callbacks' )
1611 }
1712 } ,
18- create : function ( context ) {
13+ create ( context ) {
1914 function checkLastParamsForCallback ( node ) {
20- const len = node . params . length - 1
21- const lastParam = node . params [ len ]
22- if (
23- lastParam &&
24- ( lastParam . name === 'callback' || lastParam . name === 'cb' )
25- ) {
15+ const lastParam = node . params [ node . params . length - 1 ] || { }
16+ if ( lastParam . name === 'callback' || lastParam . name === 'cb' ) {
2617 context . report ( { node : lastParam , message : errorMessage } )
2718 }
2819 }
2920 function isInsideYieldOrAwait ( ) {
30- return context . getAncestors ( ) . some ( function ( parent ) {
21+ return context . getAncestors ( ) . some ( parent => {
3122 return (
3223 parent . type === 'AwaitExpression' || parent . type === 'YieldExpression'
3324 )
3425 } )
3526 }
3627 return {
37- CallExpression : function ( node ) {
38- // callbacks aren't allowed
28+ CallExpression ( node ) {
29+ // Callbacks aren't allowed.
3930 if ( node . callee . name === 'cb' || node . callee . name === 'callback' ) {
4031 context . report ( { node, message : errorMessage } )
4132 return
4233 }
4334
44- // thennables aren't allowed either
35+ // Then-ables aren't allowed either.
4536 const args = node . arguments
46- const num = args . length - 1
47- const arg = num > - 1 && node . arguments && node . arguments [ num ]
37+ const lastArgIndex = args . length - 1
38+ const arg = lastArgIndex > - 1 && node . arguments [ lastArgIndex ]
4839 if (
4940 ( arg && arg . type === 'FunctionExpression' ) ||
5041 arg . type === 'ArrowFunctionExpression'
5142 ) {
43+ // Ignore event listener callbacks.
44+ if (
45+ node . callee . property &&
46+ ( node . callee . property . name === 'on' ||
47+ node . callee . property . name === 'once' )
48+ ) {
49+ return
50+ }
5251 if ( arg . params && arg . params [ 0 ] && arg . params [ 0 ] . name === 'err' ) {
5352 if ( ! isInsideYieldOrAwait ( ) ) {
5453 context . report ( { node : arg , message : errorMessage } )
0 commit comments