[Vuejs]-Vue.js – Using Promises on Websocket?

0👍

You can create a Promise that resolves upon open, and rejects upon error or close.

const ws = new WebSocket(`ws://${location.host}/ws/ssh?${params}`);
const ready = new Promise((resolve, reject) => {
    ws.onopen = resolve;
    ws.onerror = reject;
    ws.onclose = reject;
});
await ready;

This will await until the websocket is open, or throw an error if the websockets closes with or without an error.

Leave a comment