javascript - Global variables and asynchronous data -


i have problem global variable n:

var n ;  socket.on('connect', function(){  socket.on('news', function  (mensaje) {   n = mensaje.data;  $('#string').val(n);  //  show  data    });      $('#string1').val(n);    // can't see anything, why?   ...});  // 

first, global variable n shows inside socket.on want show out function.

the problem socket.on has not finished (or invoked callback) when problematic line executes. because on asynchronous operation: returns immediately , invokes callback "later" when data received. data can used after on callback run.

here example of execution order, 1 "runs" before 2, before 3, etc.:

// 1 var n; socket.on('connect', function(){   // 2   socket.on('news', function  (mensaje) { // "on callback"     // 4     n = mensaje.data;     // 5     $('#string').val(n);   });   // 3 - note occurs *before* 4 & 5   //     run in asynchronous callback   //     n has not been assigned yet   $('#string1').val(n); }) 

the solution only use variable after has been assigned, guaranteed after on callback runs. (promises make easy chain bunch of dependent asynchronous operations.)


Comments

Popular posts from this blog

Issues changing the value of an element in an array in matlab -

php - MySQLi binding parameters in a prepared statement doesn't work unless inserted after "WHERE" -

vb.net - Alternative to the T-SQL AS keyword -