-1

I was wondering whether there is a method that can let me print out value like this?

socket.emit('location', "Hostel");

socket.on('resultOfLocation', function(msg){
    console.log(msg);   //This can print out value successfully
});
console.log(msg);  //Result is undefined. How can print out value at here?
DavidODW
  • 417
  • 4
  • 16

1 Answers1

1

There is no workaround because socket.on's callback function will be called asynchronously after the rest of the script is run. Therefore the line with undefined result will be run before any code in the callback.

twinlakes
  • 9,438
  • 6
  • 31
  • 42
  • even if `socket.on` was a synchronous function, `msg` outside the `function(msg)` is not defined – Igor Dec 14 '14 at 01:38
  • @Igor true, but we could define it outside the function and we would not be closer to a solution. – twinlakes Dec 14 '14 at 01:40
  • @Igor Since I cannot `msg` outside the `function(msg)`, so I just get all my task done inside the function. I think that is the only way I use it to update my data. – DavidODW Dec 14 '14 at 04:35