Alex's Slip-box

These are my org-mode notes in sort of Zettelkasten style

Wait for WebSocket open

When constructing a WebSocket, a network call is immediately made to establish an open connection with the resource at the URL provided to the constructor. That can take some time, and it might be useful in some cases to be able to await this before attempting to send messages or other things the application might do that depends on the open WS connection.

In addition to being able to set the onopen property on a WebSocket, we can also use addEventListener since WebSocket inherits from EventTarget. Leveraging the open event and the readyState property, we can do something like this:

class WebSocketWrapper {

  constructor(url) {
    this.url = url

  open() {
    this.socket = new WebSocket(this.url);

    return new Promise((resolve) => {
      if (this.socket && this.socket.readyState !== this.socket.OPEN) {
        this.socket.addEventListener('open', () => { resolve() });
      } else {

const myWS = new WebSocketWrapper("wss://");

The open method returns a Promise that can be awaited. If the WebSocket is not already open, an event listener is added for the open event which resolves the Promise. Otherwise, if the WebSocket is already open, just resolve.

See also this post.

Search Results