javascript - Socket.IO node js saving data to client -


currently want save int assigned server client

server side:

socket.emit('clientid', id); 

client side:

var clientid; socket.on('clientid', function(data){      clientid = data; }); 

however, when use console.log(clientid); outside function, becomes undefined. there solution this. thanks

it's not becomes undefined outside of function it's not defined yet. didn't show how want access outside of function if it's this:

var clientid; socket.on('clientid', function(data){      clientid = data; }); console.log(clientid); 

then console.log line run before clientid = data same variable, it's not defined yet.

you need access variable socket.on handler, or function run handler, or after handler has been run.

it's hard tell more specific since didn't how want access variable , want it. can see example put on github see if you:

it looks this:

var l = document.getelementbyid('l'); var log = function (m) {     var = document.createelement('li');     i.innertext = new date().toisostring()+' '+m;     l.appendchild(i); } log('opening socket.io connection'); var s = io(); s.on('connect_error', function (m) { log("error"); }); s.on('connect', function (m) { log("socket.io connection open"); }); s.on('message', function (m) { log(m); }); 

here, log function called within handler guaranteed called after message has been passed. data passed argument function use global variable well.

update

here simpler example:

var clientid; socket.on('clientid', function (data) {      clientid = data;      clientready(); });  function clientready() {     // can access here:     console.log(clientid); } 

here can access variable in clientready function outside of on handler. think of window.onload handler:

window.onload = function() {     // ... }; 

or $(document).ready() in jquery:

$(document).ready(function () {     // ... }); 

it piece of code gets called on moment guarantee need ready.

another example using promise:

var clientidpromise = new promise(function (resolve, reject) {     socket.on('clientid', function (data) {         resolve(data);     }); });  // everywhere in code can access as: clientidpromise.then(function (clientid) {     // have access clientid here }); 

or shorter, using fat arrow notation:

var clientidpromise = new promise(     (res, rej) => socket.on('clientid', data => res(data));  // , somewhere else: clientidpromise.then(clientid => {     // have access clientid here }); 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -