UNPKG

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