1717 * limitations under the License.
1818 */
1919
20- import { newError } from " ../error" ;
20+ import { newError } from ' ../error' ;
2121
2222const ENCRYPTION_ON = "ENCRYPTION_ON" ;
2323const ENCRYPTION_OFF = "ENCRYPTION_OFF" ;
@@ -125,6 +125,8 @@ function trimAndVerify(string, name, url) {
125125}
126126
127127function promiseOrTimeout ( timeout , otherPromise , onTimeout ) {
128+ let resultPromise = null ;
129+
128130 const timeoutPromise = new Promise ( ( resolve , reject ) => {
129131 const id = setTimeout ( ( ) => {
130132 if ( onTimeout && typeof onTimeout === 'function' ) {
@@ -134,10 +136,22 @@ function promiseOrTimeout(timeout, otherPromise, onTimeout) {
134136 reject ( newError ( `Operation timed out in ${ timeout } ms.` ) ) ;
135137 } , timeout ) ;
136138
137- otherPromise . then ( ( ) => clearTimeout ( id ) , ( ) => clearTimeout ( id ) ) ;
139+ // this "executor" function is executed immediately, even before the Promise constructor returns
140+ // thus it's safe to initialize resultPromise variable here, where timeout id variable is accessible
141+ resultPromise = otherPromise . then ( result => {
142+ clearTimeout ( id ) ;
143+ return result ;
144+ } ) . catch ( error => {
145+ clearTimeout ( id ) ;
146+ throw error ;
147+ } ) ;
138148 } ) ;
139149
140- return Promise . race ( [ otherPromise , timeoutPromise ] ) ;
150+ if ( resultPromise == null ) {
151+ throw new Error ( 'Result promise not initialized' ) ;
152+ }
153+
154+ return Promise . race ( [ resultPromise , timeoutPromise ] ) ;
141155}
142156
143157export {
0 commit comments