How can I carry out a Synchronous WebScoket Connection

Viewed 45

I wrote a piece of code that connects using webscokets. However, when I am looking for the connection to close, it carries on with the execution without waiting for the connection to close. In other words the 'connection.onclose' is asynchronous, how can I make it synchronous. I don't code much in java. So I would find it very helpful if someone re-writes this piece of code in a synchronous way.

var connection = new WebSocket('wss://IP:PORT');
connection.onclose = function (event) {
    e = (event.code);

}
alert('message!')
1 Answers

JavaScript doesn't allow you to wait in synchronous code, so make it asynchronous. If you need it to be synchronous, then it is possible, but not ideal.
Synchronous

var connection = new WebSocket('wss://IP:PORT');
var e;
function nextstuff() {
    alert('message!');
};
connection.onclose = function (event) {
    e = (event.code);
    nextstuff();
};

Asynchronous

(async function() {
    var connection = new WebSocket('wss://IP:PORT');
    var e;
    await new Promise(function(res) {
        connection.onclose = function (event) {
            e = event.code;
            res(event);
        }
    });
    alert('message!');
})();
Related