prefer-await-to-then.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * Rule: prefer-await-to-then
  3. * Discourage using then()/catch()/finally() and instead use async/await.
  4. */
  5. 'use strict'
  6. const getDocsUrl = require('./lib/get-docs-url')
  7. module.exports = {
  8. meta: {
  9. type: 'suggestion',
  10. docs: {
  11. url: getDocsUrl('prefer-await-to-then'),
  12. },
  13. },
  14. create(context) {
  15. /** Returns true if node is inside yield or await expression. */
  16. function isInsideYieldOrAwait() {
  17. return context.getAncestors().some((parent) => {
  18. return (
  19. parent.type === 'AwaitExpression' || parent.type === 'YieldExpression'
  20. )
  21. })
  22. }
  23. /**
  24. * Returns true if node is created at the top-level scope.
  25. * Await statements are not allowed at the top level,
  26. * only within function declarations.
  27. */
  28. function isTopLevelScoped() {
  29. return context.getScope().block.type === 'Program'
  30. }
  31. return {
  32. MemberExpression(node) {
  33. if (isTopLevelScoped() || isInsideYieldOrAwait()) {
  34. return
  35. }
  36. // if you're a then/catch/finally expression then you're probably a promise
  37. if (
  38. node.property &&
  39. (node.property.name === 'then' ||
  40. node.property.name === 'catch' ||
  41. node.property.name === 'finally')
  42. ) {
  43. context.report({
  44. node: node.property,
  45. message: 'Prefer await to then()/catch()/finally().',
  46. })
  47. }
  48. },
  49. }
  50. },
  51. }