UNPKG

2.87 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to disallow async functions which have no `await` expression.
3 * @author Toru Nagashima
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const astUtils = require("../ast-utils");
13
14//------------------------------------------------------------------------------
15// Helpers
16//------------------------------------------------------------------------------
17
18/**
19 * Capitalize the 1st letter of the given text.
20 *
21 * @param {string} text - The text to capitalize.
22 * @returns {string} The text that the 1st letter was capitalized.
23 */
24function capitalizeFirstLetter(text) {
25 return text[0].toUpperCase() + text.slice(1);
26}
27
28//------------------------------------------------------------------------------
29// Rule Definition
30//------------------------------------------------------------------------------
31
32module.exports = {
33 meta: {
34 docs: {
35 description: "disallow async functions which have no `await` expression",
36 category: "Best Practices",
37 recommended: false
38 },
39 schema: []
40 },
41
42 create(context) {
43 const sourceCode = context.getSourceCode();
44 let scopeInfo = null;
45
46 /**
47 * Push the scope info object to the stack.
48 *
49 * @returns {void}
50 */
51 function enterFunction() {
52 scopeInfo = {
53 upper: scopeInfo,
54 hasAwait: false
55 };
56 }
57
58 /**
59 * Pop the top scope info object from the stack.
60 * Also, it reports the function if needed.
61 *
62 * @param {ASTNode} node - The node to report.
63 * @returns {void}
64 */
65 function exitFunction(node) {
66 if (node.async && !scopeInfo.hasAwait && !astUtils.isEmptyFunction(node)) {
67 context.report({
68 node,
69 loc: astUtils.getFunctionHeadLoc(node, sourceCode),
70 message: "{{name}} has no 'await' expression.",
71 data: {
72 name: capitalizeFirstLetter(
73 astUtils.getFunctionNameWithKind(node)
74 )
75 }
76 });
77 }
78
79 scopeInfo = scopeInfo.upper;
80 }
81
82 return {
83 FunctionDeclaration: enterFunction,
84 FunctionExpression: enterFunction,
85 ArrowFunctionExpression: enterFunction,
86 "FunctionDeclaration:exit": exitFunction,
87 "FunctionExpression:exit": exitFunction,
88 "ArrowFunctionExpression:exit": exitFunction,
89
90 AwaitExpression() {
91 scopeInfo.hasAwait = true;
92 }
93 };
94 }
95};