2023-12-18 13:12:25 +08:00
|
|
|
'use strict'
|
|
|
|
|
|
|
|
const getDocsUrl = require('./lib/get-docs-url')
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
meta: {
|
2024-01-16 21:26:16 +08:00
|
|
|
type: 'suggestion',
|
2023-12-18 13:12:25 +08:00
|
|
|
docs: {
|
2024-01-16 21:26:16 +08:00
|
|
|
url: getDocsUrl('prefer-await-to-callbacks'),
|
2023-12-18 13:12:25 +08:00
|
|
|
},
|
|
|
|
messages: {
|
2024-01-16 21:26:16 +08:00
|
|
|
error: 'Avoid callbacks. Prefer Async/Await.',
|
|
|
|
},
|
2023-12-18 13:12:25 +08:00
|
|
|
},
|
|
|
|
create(context) {
|
|
|
|
function checkLastParamsForCallback(node) {
|
|
|
|
const lastParam = node.params[node.params.length - 1] || {}
|
|
|
|
if (lastParam.name === 'callback' || lastParam.name === 'cb') {
|
|
|
|
context.report({ node: lastParam, messageId: 'error' })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
function isInsideYieldOrAwait() {
|
2024-01-16 21:26:16 +08:00
|
|
|
return context.getAncestors().some((parent) => {
|
2023-12-18 13:12:25 +08:00
|
|
|
return (
|
|
|
|
parent.type === 'AwaitExpression' || parent.type === 'YieldExpression'
|
|
|
|
)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
CallExpression(node) {
|
|
|
|
// Callbacks aren't allowed.
|
|
|
|
if (node.callee.name === 'cb' || node.callee.name === 'callback') {
|
|
|
|
context.report({ node, messageId: 'error' })
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Then-ables aren't allowed either.
|
|
|
|
const args = node.arguments
|
|
|
|
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
|
|
|
|
}
|
2024-01-16 21:26:16 +08:00
|
|
|
if (
|
|
|
|
arg.params &&
|
|
|
|
arg.params[0] &&
|
|
|
|
(arg.params[0].name === 'err' || arg.params[0].name === 'error')
|
|
|
|
) {
|
2023-12-18 13:12:25 +08:00
|
|
|
if (!isInsideYieldOrAwait()) {
|
|
|
|
context.report({ node: arg, messageId: 'error' })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
FunctionDeclaration: checkLastParamsForCallback,
|
|
|
|
FunctionExpression: checkLastParamsForCallback,
|
2024-01-16 21:26:16 +08:00
|
|
|
ArrowFunctionExpression: checkLastParamsForCallback,
|
2023-12-18 13:12:25 +08:00
|
|
|
}
|
2024-01-16 21:26:16 +08:00
|
|
|
},
|
2023-12-18 13:12:25 +08:00
|
|
|
}
|