The WebSocketStream API is a modern WebSocket API that is based on web streams. It's a successor to the existing WebSocket API that is based on events. The new API solves a long-standing issue with the existing WebSocket API: backpressure. Events could be dispatched as fast as the browser wants, without giving the developer any way to pause event dispatch. This meant it is easy to overload the JS thread if you do some computation on every event. The new API solves this by using a ReadableStream as its receiving (readable) end, and a WritableStream as its sending (writable) end. Because a developer always has to “request” the next item from the stream, the browser can’t flood the script with events unasked.
In your case, it seems like you're trying to establish a connection using WebSocketStream and if the connection fails, you want to retry the connection after a delay. However, the issue with your code is that you're not awaiting the connection to be established. The WebSocketStream constructor returns immediately, but the connection is established asynchronously. You need to await the wss.connection promise, which will resolve when the connection is established or reject if the connection cannot be established.
Here's how you can modify your code:
async function webSocketStream_Connection() {
try {
const wss = new WebSocketStream("wss://localhost");
const { writable, readable } = await wss.connection;
} catch (err) {
console.error("Failed to connect, retrying in 5 seconds", err);
setTimeout(webSocketStream_Connection, 5000);
}
}
webSocketStream_Connection();
In this code, if the connection cannot be established (for example, if the