prefer-await-to-callbacks.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict'
  2. const getDocsUrl = require('./lib/get-docs-url')
  3. module.exports = {
  4. meta: {
  5. type: 'suggestion',
  6. docs: {
  7. url: getDocsUrl('prefer-await-to-callbacks'),
  8. },
  9. messages: {
  10. error: 'Avoid callbacks. Prefer Async/Await.',
  11. },
  12. },
  13. create(context) {
  14. function checkLastParamsForCallback(node) {
  15. const lastParam = node.params[node.params.length - 1] || {}
  16. if (lastParam.name === 'callback' || lastParam.name === 'cb') {
  17. context.report({ node: lastParam, messageId: 'error' })
  18. }
  19. }
  20. function isInsideYieldOrAwait() {
  21. return context.getAncestors().some((parent) => {
  22. return (
  23. parent.type === 'AwaitExpression' || parent.type === 'YieldExpression'
  24. )
  25. })
  26. }
  27. return {
  28. CallExpression(node) {
  29. // Callbacks aren't allowed.
  30. if (node.callee.name === 'cb' || node.callee.name === 'callback') {
  31. context.report({ node, messageId: 'error' })
  32. return
  33. }
  34. // Then-ables aren't allowed either.
  35. const args = node.arguments
  36. const lastArgIndex = args.length - 1
  37. const arg = lastArgIndex > -1 && node.arguments[lastArgIndex]
  38. if (
  39. (arg && arg.type === 'FunctionExpression') ||
  40. arg.type === 'ArrowFunctionExpression'
  41. ) {
  42. // Ignore event listener callbacks.
  43. if (
  44. node.callee.property &&
  45. (node.callee.property.name === 'on' ||
  46. node.callee.property.name === 'once')
  47. ) {
  48. return
  49. }
  50. if (
  51. arg.params &&
  52. arg.params[0] &&
  53. (arg.params[0].name === 'err' || arg.params[0].name === 'error')
  54. ) {
  55. if (!isInsideYieldOrAwait()) {
  56. context.report({ node: arg, messageId: 'error' })
  57. }
  58. }
  59. }
  60. },
  61. FunctionDeclaration: checkLastParamsForCallback,
  62. FunctionExpression: checkLastParamsForCallback,
  63. ArrowFunctionExpression: checkLastParamsForCallback,
  64. }
  65. },
  66. }