我在我的React应用程序中使用Websockets,我必须连接到一个web套接字,然后一旦连接就发送一条消息。但是我的代码不能同步工作
就是这里
ws = new WebSocket(uri);
ws.send('my msg');
有没有办法等待连接建立和就绪状态改变!谢谢!
发布于 2018-08-14 02:40:23
我正在执行以下操作,以准备我的WebSocket在许多其他地方使用,而不仅仅是在WebSocket readyState更改后立即使用:
// https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
const sleep = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
};
// (inside of async function)...
const ws = new WebSocket(<webSocketServerUri>);
let timeToConnect = 0;
while (ws.readyState !== ws.OPEN) {
await sleep(1);
++timeToConnect;
};
console.log('The WebSocket took ' + timeToConnect + ' milliseconds to connect.');
// (inside of async function)...
// ...
// (some other place in the code where 'ws' is accessible)...
ws.send('my msg');
// (some other place in the code where 'ws' is accessible)...
https://stackoverflow.com/questions/44064603
复制相似问题