prefer-await-to-then.js 1.2 KB

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