Home > Back-end >  Wait for websocket to connect before terminating function
Wait for websocket to connect before terminating function

Time:11-09

I'm using Jest to test my server's status and I've been trying to use setTimeout, delays, while loops to check if the readyState changes from 0 - CONNECTING to 3 - CLOSED or 1 - OPEN. Just one problem, and that is that I've tried to use event listeners but since that gets executed later or never in this scenario after the function terminates, Jest provides an error

I've tried different functions like these ones

function checkServerStatus() {
    const ws = new WebSocket('ws://127.0.0.1:8080');
    let a;
    ws.onopen = () => {
        a = ws.readyState;
        ws.close();
    }
    return a;
}

CodePudding user response:

Javascript does not work the way you're asking it to. ws.onopen() is an non-blocking event handler. You're just assigning a function that will be called sometime in the future and there is no way to make checkServerStatus() wait for that function to be called before the function returns. This is the non-blocking, event-driven nature of doing networking in Javascript.

Instead, you need to design your logic based on event-driven programming. In this case, you have to let your function return when it naturally returns and then you need to notify the caller when you have the value you want. You can notify them either with a callback function an event or with a promise.

Since promises are the modern way to do asynchronous notification in Javascript, here's an example using a promise:

function checkServerStatus() {
    return new Promise((resolve, reject) => {
        const ws = new WebSocket('ws://127.0.0.1:8080');
        ws.onopen = () => {
            resolve(ws.readyState);
            ws.close();
        };
        ws.onerror = (e) => {
            reject(e);
        };
    });
}

You could then call this function like this:

checkServerStatus().then(val => {
   console.log(val);
}).catch(err => {
   console.log(err);
});
  • Related