0

Currently my code looks as follows, because a WebSocket connection is initiated when I invoke the WebSocket constructor.

import WebSocket = require('isomorphic-ws');

let socket = new WebSocket(`${host}:${port}`);
socket.onerror = (event: { error: any }): void => {
    console.log('good');
};
socket.onopen = (): void => {
    console.log('bad');
};

This feels a little messy to me. Is it possible to rewrite this so that I create a WebSocket object first, then setup handlers and last, connect? Something like:

import WebSocket = require('isomorphic-ws');

let socket = new WebSocket(`${host}:${port}`);
socket.onerror = (event: { error: any }): void => {
    console.log('good');
};
socket.onopen = (): void => {
    console.log('bad');
};
socket.connect();
user1283776
  • 19,640
  • 49
  • 136
  • 276
  • 1
    In a word, no, because that is not how [the WebSocket API](https://www.w3.org/TR/websockets/) works. Besides, you do not need to worry about this anyway, because the WebSocket object will internally queue up the connection attempt, and subsequent events, to run asynchronously in the background, so it will not actually try to call your event handlers until some later time long after you have assigned them. – Remy Lebeau Feb 14 '19 at 00:53
  • Related: [Why does WebSocket event listeners work if they are registered after events are fired?](https://stackoverflow.com/questions/54663970/) – Remy Lebeau Feb 14 '19 at 01:06

0 Answers0