UNPKG

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