0

目前我的代码如下所示,因为在调用 WebSocket 构造函数时会启动 WebSocket 连接。

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');
};

这对我来说有点乱。是否可以重写它以便我首先创建一个 WebSocket 对象,然后设置处理程序,最后连接?就像是:

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();
4

0 回答 0