DEV Community

loading...

Discussion on: Wait for the WebSocket connection to be open, before sending a message

Collapse
fabiwlf profile image
Fabian Wolf • Edited

The while loop stops the code execution in my case.

Better use something like this, works fine for me:

const waitForOpenSocket = (socket) => {
  return new Promise((resolve) => {
    if (socket.readyState !== socket.OPEN) {
      socket.on("open", _ => {
        resolve();
      });
    } else {
      resolve();
    }
  });
}
Enter fullscreen mode Exit fullscreen mode
Collapse
engelmav profile image
Vincent Engelmann • Edited

This was the best solution for me. Minor tweak, this looks like it's for socketio. The following is for vanilla websockets:


async waitForOpenSocket(socket) {
    return new Promise((resolve) => {
      if (socket.readyState !== socket.OPEN) {
        socket.addEventListener("open", (_) => {
          resolve();
        })
      } else {
        resolve();
      }
    });
  }
Enter fullscreen mode Exit fullscreen mode