0

If the variable value is global why do i get undefined when i console.log() it out of socket.on('Led_1')? `

var io = require('socket.io-client');
var value;
var socket = io.connect('http://105.155.150.85/');

socket.on('Led_1',function(data){
    value = data.message;
    console.log(value); // Here it shows the value.
});

console.log(value); // here it shows undefined.

`

  • Because the last `console.log(value); // here it shows undefined.` will run before the `socket.on()`, hence not yet assigned anything – Asons Jun 23 '18 at 23:33
  • Thanks for your response, so how can make this work? – younes sami Jun 29 '18 at 18:13
  • Follow the guidelines at the dupe link – Asons Jun 29 '18 at 18:16
  • the think that i want to understand is what would happen if i call an Asynchronous function inside of a Synchronous like this:displayState_RGB(){ socket.on('Led_RGB',function(data){ val = data.message; console.log('RGB: '+val); //Le Cercle s'affiche avec la couleur de la LED RGB. return(); }); } – younes sami Jun 29 '18 at 18:33
  • Simply put, an async method will generally allow the code to continue (non-blocking) on the next line, and the async mehtod will return when it's done, and if one depend on a returned value that that async method will return, one will get an error as you did here. – Asons Jun 29 '18 at 18:37

0 Answers0