Skip to content

Commit

Permalink
fix(eslint-plugin): [return-await] await in a normal function (#1962)
Browse files Browse the repository at this point in the history
  • Loading branch information
yinm committed May 4, 2020
1 parent 05476ca commit f82fd7b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
25 changes: 25 additions & 0 deletions packages/eslint-plugin/src/rules/return-await.ts
Expand Up @@ -7,6 +7,15 @@ import * as tsutils from 'tsutils';
import * as ts from 'typescript';
import * as util from '../util';

interface ScopeInfo {
hasAsync: boolean;
}

type FunctionNode =
| TSESTree.FunctionDeclaration
| TSESTree.FunctionExpression
| TSESTree.ArrowFunctionExpression;

export default util.createRule({
name: 'return-await',
meta: {
Expand Down Expand Up @@ -40,6 +49,14 @@ export default util.createRule({
const checker = parserServices.program.getTypeChecker();
const sourceCode = context.getSourceCode();

let scopeInfo: ScopeInfo | null = null;

function enterFunction(node: FunctionNode): void {
scopeInfo = {
hasAsync: node.async,
};
}

function inTryCatch(node: ts.Node): boolean {
let ancestor = node.parent;

Expand Down Expand Up @@ -185,6 +202,10 @@ export default util.createRule({
}

return {
FunctionDeclaration: enterFunction,
FunctionExpression: enterFunction,
ArrowFunctionExpression: enterFunction,

'ArrowFunctionExpression[async = true]:exit'(
node: TSESTree.ArrowFunctionExpression,
): void {
Expand All @@ -197,6 +218,10 @@ export default util.createRule({
}
},
ReturnStatement(node): void {
if (!scopeInfo || !scopeInfo.hasAsync) {
return;
}

const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);

const { expression } = originalNode;
Expand Down
14 changes: 14 additions & 0 deletions packages/eslint-plugin/tests/rules/return-await.test.ts
Expand Up @@ -180,6 +180,20 @@ ruleTester.run('return-await', rule, {
}
`,
},
{
options: ['always'],
code: `
declare function foo(): Promise<boolean>;
function bar(baz: boolean): Promise<boolean> | boolean {
if (baz) {
return true;
} else {
return foo();
}
}
`,
},
{
code: `
async function test(): Promise<string> {
Expand Down

0 comments on commit f82fd7b

Please sign in to comment.