Имеется следующий код:
const WebSocket = require('ws');
class WebSocketExtended extends WebSocket {
async command(data, status = null, timeout = 10000) {
return new Promise(async (resolve, reject) => {
await new Promise((resolve, reject) => {
if (this.readyState === 1) {
resolve();
}
this.addEventListener('open', () => resolve());
setTimeout(() => reject(`WebSocket timeout ${timeout}`), timeout);
});
if (this.readyState !== 1) {
reject(`Error WebSocket`);
}
if (!data) {
reject(`Empty data`);
}
const unsubscribe = () => {
if (reference) {
clearTimeout(reference);
}
this.removeEventListener('message', message, false);
};
const reference = setTimeout(() => {
unsubscribe();
reject(`WebSocket timeout ${timeout}`);
}, timeout);
const message = (event) => {
let json;
try {
json = JSON.parse(event?.data);
} catch (error) {
unsubscribe();
reject(error);
}
if (!status || json?.status?.[0] === status) {
unsubscribe();
resolve(json);
}
};
let string;
try {
string = JSON.stringify(data);
} catch (error) {
unsubscribe();
reject(error);
}
this.addEventListener('message', message);
this.send(string);
});
}
}
const socket = new WebSocketExtended('wss://some.com:8000');
await socket.command({
auth_token: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='
}, 2999);
На мой взгляд, можно сделать проще и лучше!
Нужна ваша помощь