@@ -88,14 +88,21 @@ namespace ts.codefix {
88
88
89
89
function getAwaitableExpression ( sourceFile : SourceFile , errorCode : number , span : TextSpan , cancellationToken : CancellationToken , program : Program ) : Expression | undefined {
90
90
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.
91
94
const expression = findAncestor ( token , node => {
92
95
if ( node . getStart ( sourceFile ) < span . start || node . getEnd ( ) > textSpanEnd ( span ) ) {
93
96
return "quit" ;
94
97
}
95
98
return isExpression ( node ) && textSpansEqual ( span , createTextSpanFromNode ( node , sourceFile ) ) ;
96
99
} ) as Expression | undefined ;
97
100
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 ;
99
106
}
100
107
101
108
function findAwaitableInitializer ( expression : Node , sourceFile : SourceFile , checker : TypeChecker ) : Expression | undefined {
@@ -116,7 +123,8 @@ namespace ts.codefix {
116
123
! declaration . initializer ||
117
124
variableStatement . getSourceFile ( ) !== sourceFile ||
118
125
hasModifier ( variableStatement , ModifierFlags . Export ) ||
119
- ! variableName ) {
126
+ ! variableName ||
127
+ ! isInsideAwaitableBody ( declaration . initializer ) ) {
120
128
return ;
121
129
}
122
130
@@ -131,6 +139,16 @@ namespace ts.codefix {
131
139
return declaration . initializer ;
132
140
}
133
141
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
+
134
152
function makeChange ( changeTracker : textChanges . ChangeTracker , errorCode : number , sourceFile : SourceFile , checker : TypeChecker , insertionSite : Expression ) {
135
153
if ( isBinaryExpression ( insertionSite ) ) {
136
154
const { left, right } = insertionSite ;
0 commit comments