prefer-await-to-then.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. 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 expression then you're probably a promise
  37. if (node.property && node.property.name === 'then') {
  38. context.report({
  39. node: node.property,
  40. message: 'Prefer await to then().',
  41. })
  42. }
  43. },
  44. }
  45. },
  46. }