Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f82fd7b

Browse files
authored
fix(eslint-plugin): [return-await] await in a normal function (typescript-eslint#1962)
1 parent 05476ca commit f82fd7b

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

packages/eslint-plugin/src/rules/return-await.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,15 @@ import * as tsutils from 'tsutils';
77
import * as ts from 'typescript';
88
import * as util from '../util';
99

10+
interface ScopeInfo {
11+
hasAsync: boolean;
12+
}
13+
14+
type FunctionNode =
15+
| TSESTree.FunctionDeclaration
16+
| TSESTree.FunctionExpression
17+
| TSESTree.ArrowFunctionExpression;
18+
1019
export default util.createRule({
1120
name: 'return-await',
1221
meta: {
@@ -40,6 +49,14 @@ export default util.createRule({
4049
const checker = parserServices.program.getTypeChecker();
4150
const sourceCode = context.getSourceCode();
4251

52+
let scopeInfo: ScopeInfo | null = null;
53+
54+
function enterFunction(node: FunctionNode): void {
55+
scopeInfo = {
56+
hasAsync: node.async,
57+
};
58+
}
59+
4360
function inTryCatch(node: ts.Node): boolean {
4461
let ancestor = node.parent;
4562

@@ -185,6 +202,10 @@ export default util.createRule({
185202
}
186203

187204
return {
205+
FunctionDeclaration: enterFunction,
206+
FunctionExpression: enterFunction,
207+
ArrowFunctionExpression: enterFunction,
208+
188209
'ArrowFunctionExpression[async = true]:exit'(
189210
node: TSESTree.ArrowFunctionExpression,
190211
): void {
@@ -197,6 +218,10 @@ export default util.createRule({
197218
}
198219
},
199220
ReturnStatement(node): void {
221+
if (!scopeInfo || !scopeInfo.hasAsync) {
222+
return;
223+
}
224+
200225
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
201226

202227
const { expression } = originalNode;

packages/eslint-plugin/tests/rules/return-await.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,20 @@ ruleTester.run('return-await', rule, {
180180
}
181181
`,
182182
},
183+
{
184+
options: ['always'],
185+
code: `
186+
declare function foo(): Promise<boolean>;
187+
188+
function bar(baz: boolean): Promise<boolean> | boolean {
189+
if (baz) {
190+
return true;
191+
} else {
192+
return foo();
193+
}
194+
}
195+
`,
196+
},
183197
{
184198
code: `
185199
async function test(): Promise<string> {

0 commit comments

Comments
 (0)