1
- /**
2
- * Rule: prefer-await-to-callbacks
3
- * Discourage using then() and instead use async/await.
4
- */
5
-
6
1
'use strict'
7
2
8
3
const getDocsUrl = require ( './lib/get-docs-url' )
@@ -15,40 +10,44 @@ module.exports = {
15
10
url : getDocsUrl ( 'prefer-await-to-callbacks' )
16
11
}
17
12
} ,
18
- create : function ( context ) {
13
+ create ( context ) {
19
14
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' ) {
26
17
context . report ( { node : lastParam , message : errorMessage } )
27
18
}
28
19
}
29
20
function isInsideYieldOrAwait ( ) {
30
- return context . getAncestors ( ) . some ( function ( parent ) {
21
+ return context . getAncestors ( ) . some ( parent => {
31
22
return (
32
23
parent . type === 'AwaitExpression' || parent . type === 'YieldExpression'
33
24
)
34
25
} )
35
26
}
36
27
return {
37
- CallExpression : function ( node ) {
38
- // callbacks aren't allowed
28
+ CallExpression ( node ) {
29
+ // Callbacks aren't allowed.
39
30
if ( node . callee . name === 'cb' || node . callee . name === 'callback' ) {
40
31
context . report ( { node, message : errorMessage } )
41
32
return
42
33
}
43
34
44
- // thennables aren't allowed either
35
+ // Then-ables aren't allowed either.
45
36
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 ]
48
39
if (
49
40
( arg && arg . type === 'FunctionExpression' ) ||
50
41
arg . type === 'ArrowFunctionExpression'
51
42
) {
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
+ }
52
51
if ( arg . params && arg . params [ 0 ] && arg . params [ 0 ] . name === 'err' ) {
53
52
if ( ! isInsideYieldOrAwait ( ) ) {
54
53
context . report ( { node : arg , message : errorMessage } )
0 commit comments