@@ -88,14 +88,21 @@ namespace ts.codefix {
8888
8989 function getAwaitableExpression ( sourceFile : SourceFile , errorCode : number , span : TextSpan , cancellationToken : CancellationToken , program : Program ) : Expression | undefined {
9090 const token = getTokenAtPosition ( sourceFile , span . start ) ;
91+ // Checker has already done work to determine that await might be possible, and has attached
92+ // related info to the node, so start by finding the expression that exactly matches up
93+ // with the diagnostic range.
9194 const expression = findAncestor ( token , node => {
9295 if ( node . getStart ( sourceFile ) < span . start || node . getEnd ( ) > textSpanEnd ( span ) ) {
9396 return "quit" ;
9497 }
9598 return isExpression ( node ) && textSpansEqual ( span , createTextSpanFromNode ( node , sourceFile ) ) ;
9699 } ) as Expression | undefined ;
97100
98- return isMissingAwaitError ( sourceFile , errorCode , span , cancellationToken , program ) ? expression : undefined ;
101+ return expression
102+ && isMissingAwaitError ( sourceFile , errorCode , span , cancellationToken , program )
103+ && isInsideAwaitableBody ( expression )
104+ ? expression
105+ : undefined ;
99106 }
100107
101108 function findAwaitableInitializer ( expression : Node , sourceFile : SourceFile , checker : TypeChecker ) : Expression | undefined {
@@ -116,7 +123,8 @@ namespace ts.codefix {
116123 ! declaration . initializer ||
117124 variableStatement . getSourceFile ( ) !== sourceFile ||
118125 hasModifier ( variableStatement , ModifierFlags . Export ) ||
119- ! variableName ) {
126+ ! variableName ||
127+ ! isInsideAwaitableBody ( declaration . initializer ) ) {
120128 return ;
121129 }
122130
@@ -131,6 +139,16 @@ namespace ts.codefix {
131139 return declaration . initializer ;
132140 }
133141
142+ function isInsideAwaitableBody ( node : Node ) {
143+ return ! ! findAncestor ( node , ancestor =>
144+ ancestor . parent && isArrowFunction ( ancestor . parent ) && ancestor . parent . body === ancestor ||
145+ isBlock ( ancestor ) && (
146+ ancestor . parent . kind === SyntaxKind . FunctionDeclaration ||
147+ ancestor . parent . kind === SyntaxKind . FunctionExpression ||
148+ ancestor . parent . kind === SyntaxKind . ArrowFunction ||
149+ ancestor . parent . kind === SyntaxKind . MethodDeclaration ) ) ;
150+ }
151+
134152 function makeChange ( changeTracker : textChanges . ChangeTracker , errorCode : number , sourceFile : SourceFile , checker : TypeChecker , insertionSite : Expression ) {
135153 if ( isBinaryExpression ( insertionSite ) ) {
136154 const { left, right } = insertionSite ;
0 commit comments