Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign value to a varaible in onmessage in websocket

I try to assign a value to a variable in onmessage function here:

socket = new WebSocket(ws_scheme +"127.0.0.1:8000/chat/");
var incomeData;
socket.onmessage = function(e) {
     incomeData='hello'+ e.data; 
     console.log('inside function:'+incomeData)
}
socket.onopen = function() { 
    socket.send(" from websocket");
}
 console.log(incomeData)

the console will show the first log as undefined and the second "inside function: hello from websocket". How can I get the variable assigned and keep the value outside the function too? Why second console.log appears first ?

like image 873
hln Avatar asked Feb 03 '26 11:02

hln


1 Answers

incomeData is defined at global scope and is not assigned anything when first is printed with console.log(incomeData) thus you get the undefined error message. Then the socket onmessage is called and you got is assigned the e.data value that console.log then prints out.

You can handle the socket.onmessage and pass the e.data to a callback function like this:

socket = new WebSocket(ws_scheme +"127.0.0.1:8000/chat/");

socket.onmessage = function(e) {
    socket_onmessage_callback(e.data);
}

socket.onopen = function() { 
    socket.send(" from websocket");
}

function socket_onmessage_callback(data) {
    console.log('inside function socket_onmessage_callback:', data)
}

You can even use incomeData global variable if you want, but I think it does not required. Can update my answer if you need to use incomeData.

like image 128
Christos Lytras Avatar answered Feb 06 '26 01:02

Christos Lytras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!