The problem is that socket.on has not finished (or invoked the callback) when the problematic line executes. This is because on
is an asynchronous operation: it returns immediately and invokes the callback "later" when the data is received. The data can only be used after the on
callback is run.
Here is an example of execution order, where 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 that this occurs *before* 4 & 5
// which run in the asynchronous callback
// so n has not been assigned yet
$('#string1').val(n);
})
The solution is to only use the variable after it has been assigned, which is only guaranteed after the on
callback runs. (Promises make it really easy to chain a bunch of dependent asynchronous operations.)