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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With