no-callback-in-promise.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * Rule: no-callback-in-promise
  3. * Avoid calling back inside of a promise
  4. */
  5. 'use strict'
  6. const getDocsUrl = require('./lib/get-docs-url')
  7. const hasPromiseCallback = require('./lib/has-promise-callback')
  8. const isInsidePromise = require('./lib/is-inside-promise')
  9. const isCallback = require('./lib/is-callback')
  10. module.exports = {
  11. meta: {
  12. type: 'suggestion',
  13. docs: {
  14. url: getDocsUrl('no-callback-in-promise'),
  15. },
  16. messages: {
  17. callback: 'Avoid calling back inside of a promise.',
  18. },
  19. schema: [
  20. {
  21. type: 'object',
  22. properties: {
  23. exceptions: {
  24. type: 'array',
  25. items: {
  26. type: 'string',
  27. },
  28. },
  29. },
  30. additionalProperties: false,
  31. },
  32. ],
  33. },
  34. create(context) {
  35. return {
  36. CallExpression(node) {
  37. const options = context.options[0] || {}
  38. const exceptions = options.exceptions || []
  39. if (!isCallback(node, exceptions)) {
  40. // in general we send you packing if you're not a callback
  41. // but we also need to watch out for whatever.then(cb)
  42. if (hasPromiseCallback(node)) {
  43. const name =
  44. node.arguments && node.arguments[0] && node.arguments[0].name
  45. if (
  46. name === 'callback' ||
  47. name === 'cb' ||
  48. name === 'next' ||
  49. name === 'done'
  50. ) {
  51. context.report({
  52. node: node.arguments[0],
  53. messageId: 'callback',
  54. })
  55. }
  56. }
  57. return
  58. }
  59. if (context.getAncestors().some(isInsidePromise)) {
  60. context.report({
  61. node,
  62. messageId: 'callback',
  63. })
  64. }
  65. },
  66. }
  67. },
  68. }