Fix race condition in WebBleConnection

WebBleConnection's constructor calls init(), which is async. Constructors can't be async, so this means that callers who instantiate WebBleConnection can end up with it in an invalid state after construction if init() hasn't completed by the time the caller tries to access class members that depend on init.

I think the cleaner solution is to push the init() call to open(), which is async, so it can just await the results of init(), and the caller can trust that after calling open(), the connection is fully initialized.

This is a second attempt (see 78a0037). The fix here is to defer emitting the connected event a by wrapping it in a setTimeout(..., 0), which prevents open() from firing the event before the client has a chance to set up an event handler for the 'connected' event. This matches the strategy we use in WebSerialConnection.
This commit is contained in:
Michael Lynch 2026-01-23 06:30:10 -05:00
parent 9a979df471
commit 97dff6c195
2 changed files with 13 additions and 5 deletions

View file

@ -9,7 +9,6 @@ class WebBleConnection extends Connection {
this.gattServer = null;
this.rxCharacteristic = null;
this.txCharacteristic = null;
this.init();
}
static async open() {
@ -36,8 +35,11 @@ class WebBleConnection extends Connection {
return null;
}
return new WebBleConnection(device);
// create connection and initialize it
const connection = new WebBleConnection(device);
await connection.init();
return connection;
}
async init() {
@ -71,8 +73,12 @@ class WebBleConnection extends Connection {
this.onFrameReceived(frame);
});
// fire connected event
await this.onConnected();
// wait to fire connected event after the caller has a chance to set up handlers
// by calling setTimeout(..., 0), we wait for the next tick of the JavaScript event
// loop.
setTimeout(async () => {
await this.onConnected();
}, 0);
}

View file

@ -16,7 +16,9 @@ class WebSerialConnection extends SerialConnection {
this.onDisconnected();
});
// fire connected callback after constructor has returned
// wait to fire connected event after the caller has a chance to set up handlers
// by calling setTimeout(..., 0), we wait for the next tick of the JavaScript event
// loop.
setTimeout(async () => {
await this.onConnected();
}, 0);