Home > Enterprise >  Websocket response data undefined in global variable
Websocket response data undefined in global variable

Time:05-21

I would like to use the global variable data and assign the WebSocket response data to it but inside the function the data is displayed outside is undefined.

How can I solve this?

var data;

client.onopen = () => {
  console.log("WebSocket Client Connected!");
};

client.onmessage = (message) => {
  data = message.data;
  console.log(data); // json data in console
};

client.onerror = function () {
  console.log("Connection Error");
};

console.log(data); // undefined

CodePudding user response:

It is because the last console.log happens before the socket event happens that why the variable is undefined if you want to see the variable you need to call it by function after the socket event emited

CodePudding user response:

The data variable is not defined at the time when console.log executes, you tried to log the variable to the console before your client received the message.

  • Related