@@ -35,6 +35,7 @@ class Codebolt {
35
35
websocket : WebSocket | null = null ;
36
36
private isReady : boolean = false ;
37
37
private readyPromise : Promise < void > ;
38
+ private readyHandlers : Array < ( ) => void | Promise < void > > = [ ] ;
38
39
39
40
/**
40
41
* @constructor
@@ -56,6 +57,15 @@ class Codebolt {
56
57
this . websocket = cbws . getWebsocket ;
57
58
this . isReady = true ;
58
59
console . log ( "Codebolt WebSocket connection established" ) ;
60
+
61
+ // Execute all registered ready handlers
62
+ for ( const handler of this . readyHandlers ) {
63
+ try {
64
+ await handler ( ) ;
65
+ } catch ( error ) {
66
+ console . error ( 'Error executing ready handler:' , error ) ;
67
+ }
68
+ }
59
69
} catch ( error ) {
60
70
console . error ( 'Failed to initialize WebSocket connection:' , error ) ;
61
71
throw error ;
@@ -106,6 +116,31 @@ class Codebolt {
106
116
utils = cbutils ;
107
117
notify = notificationFunctions ;
108
118
119
+ /**
120
+ * Sets up a handler function to be executed when the WebSocket connection is established.
121
+ * If the connection is already established, the handler will be executed immediately.
122
+ * @param {Function } handler - The handler function to call when the connection is ready.
123
+ * @returns {void }
124
+ */
125
+ onReady ( handler : ( ) => void | Promise < void > ) {
126
+ if ( this . isReady ) {
127
+ // If already ready, execute the handler immediately
128
+ try {
129
+ const result = handler ( ) ;
130
+ if ( result instanceof Promise ) {
131
+ result . catch ( error => {
132
+ console . error ( 'Error in ready handler:' , error ) ;
133
+ } ) ;
134
+ }
135
+ } catch ( error ) {
136
+ console . error ( 'Error in ready handler:' , error ) ;
137
+ }
138
+ } else {
139
+ // If not ready yet, add to the list of handlers to execute when ready
140
+ this . readyHandlers . push ( handler ) ;
141
+ }
142
+ }
143
+
109
144
/**
110
145
* Sets up a listener for incoming messages with a direct handler function.
111
146
* @param {Function } handler - The handler function to call when a message is received.
0 commit comments