2

I'm a bit stuck :/ I don't know how to initialize a variable inside an anonymous function, called when the websocket receives a message from the server. Is there a way to use the received the message received outside the function? There is a way to do that:

// Very simplified code:
var x;
socket.onmessage = function (e) { 
    x = messageReceived; 
}
console.log(x) // print the message received. 

I hope somebody can help me :)

Bastian Nanchen
  • 672
  • 1
  • 13
  • 24
  • 2
    Your attempt to `console.log` it is happening before the request completes; the former is synchronous while the latter is asynchronous. You need to use callbacks any time you want to use data returned by an asynchronous request. – Mitya Oct 19 '16 at 13:30

0 Answers0