When using my client-websocket, I have the ability to register callbacks for specific events such as opening or closing the connection. In these callbacks, I aim to resolve a promise in order to await the events from an external source, especially for unit tests. The code snippet below illustrates what I am trying to achieve:
let wsOnOpenPromise = new Promise<void>(resolve => { /* ??? */ });
let wsOnClosePromise = new Promise<void>(resolve => { /* ??? */ });
const ws = new WebsocketBuilder(url)
.onOpen((i, e) => { /* resolve wsOnOpenPromise here */ })
.onClose((i, e) => { /* resolve wsOnClosePromise here */ })
.build();
await wsOnOpenPromise;
shutdownServer(); /* Shutdown the server here, the on-close event should fire */
await wsOnClosePromise;
How can I accomplish this? It appears that I need to define the promises upfront and resolve them within the callbacks so they can be awaited as shown in the code snippet.