@@ -31,6 +31,8 @@ export class HubConnection {
31
31
private id : number ;
32
32
private closedCallbacks : Array < ( error ?: Error ) => void > ;
33
33
private receivedHandshakeResponse : boolean ;
34
+ private handshakeResolver ! : ( value ?: PromiseLike < { } > ) => void ;
35
+ private handshakeRejecter ! : ( reason ?: any ) => void ;
34
36
private connectionState : HubConnectionState ;
35
37
36
38
// The type of these a) doesn't matter and b) varies when building in browser and node contexts
@@ -106,6 +108,11 @@ export class HubConnection {
106
108
this . logger . log ( LogLevel . Debug , "Starting HubConnection." ) ;
107
109
108
110
this . receivedHandshakeResponse = false ;
111
+ // Set up the promise before any connection is started otherwise it could race with received messages
112
+ const handshakePromise = new Promise ( ( resolve , reject ) => {
113
+ this . handshakeResolver = resolve ;
114
+ this . handshakeRejecter = reject ;
115
+ } ) ;
109
116
110
117
await this . connection . start ( this . protocol . transferFormat ) ;
111
118
@@ -120,6 +127,8 @@ export class HubConnection {
120
127
this . resetTimeoutPeriod ( ) ;
121
128
this . resetKeepAliveInterval ( ) ;
122
129
130
+ // Wait for the handshake to complete before marking connection as connected
131
+ await handshakePromise ;
123
132
this . connectionState = HubConnectionState . Connected ;
124
133
}
125
134
@@ -388,19 +397,23 @@ export class HubConnection {
388
397
// We don't want to wait on the stop itself.
389
398
// tslint:disable-next-line:no-floating-promises
390
399
this . connection . stop ( error ) ;
400
+ this . handshakeRejecter ( error ) ;
391
401
throw error ;
392
402
}
393
403
if ( responseMessage . error ) {
394
404
const message = "Server returned handshake error: " + responseMessage . error ;
395
405
this . logger . log ( LogLevel . Error , message ) ;
396
406
407
+ this . handshakeRejecter ( message ) ;
397
408
// We don't want to wait on the stop itself.
398
409
// tslint:disable-next-line:no-floating-promises
399
410
this . connection . stop ( new Error ( message ) ) ;
411
+ throw new Error ( message ) ;
400
412
} else {
401
413
this . logger . log ( LogLevel . Debug , "Server handshake complete." ) ;
402
414
}
403
415
416
+ this . handshakeResolver ( ) ;
404
417
return remainingData ;
405
418
}
406
419
0 commit comments