forked from eslint-community/eslint-plugin-promise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathno-callback-in-promise.js
99 lines (92 loc) · 2.59 KB
/
no-callback-in-promise.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* Rule: no-callback-in-promise
* Avoid calling back inside of a promise
*/
'use strict'
const { getAncestors } = require('./lib/eslint-compat')
const getDocsUrl = require('./lib/get-docs-url')
const isInsidePromise = require('./lib/is-inside-promise')
const isCallback = require('./lib/is-callback')
const CB_BLACKLIST = ['callback', 'cb', 'next', 'done']
const TIMEOUT_WHITELIST = [
'setImmediate',
'setTimeout',
'requestAnimationFrame',
'nextTick',
]
const isInsideTimeout = (node) => {
const isFunctionExpression =
node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression'
const parent = node.parent || {}
const callee = parent.callee || {}
const name = (callee.property && callee.property.name) || callee.name || ''
const parentIsTimeout = TIMEOUT_WHITELIST.includes(name)
const isInCB = isFunctionExpression && parentIsTimeout
return isInCB
}
module.exports = {
meta: {
type: 'suggestion',
docs: {
description:
'Disallow calling `cb()` inside of a `then()` (use [util.callbackify][] instead).',
url: getDocsUrl('no-callback-in-promise'),
},
messages: {
callback: 'Avoid calling back inside of a promise.',
},
schema: [
{
type: 'object',
properties: {
exceptions: {
type: 'array',
items: {
type: 'string',
},
},
timeoutsErr: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
},
create(context) {
const { timeoutsErr = false } = context.options[0] || {}
return {
CallExpression(node) {
const options = context.options[0] || {}
const exceptions = options.exceptions || []
if (!isCallback(node, exceptions)) {
const callingName = node.callee.name || node.callee.property?.name
const name =
node.arguments && node.arguments[0] && node.arguments[0].name
if (
!exceptions.includes(name) &&
CB_BLACKLIST.includes(name) &&
(timeoutsErr || !TIMEOUT_WHITELIST.includes(callingName))
) {
context.report({
node: node.arguments[0],
messageId: 'callback',
})
}
return
}
const ancestors = getAncestors(context, node)
if (
ancestors.some(isInsidePromise) &&
(timeoutsErr || !ancestors.some(isInsideTimeout))
) {
context.report({
node,
messageId: 'callback',
})
}
},
}
},
}