Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [return-await] await in a normal function #1962

Merged
merged 3 commits into from May 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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