I'm new to JavaScript, and still not familiar with asynchronous functions...
I'm working with node.js to create a chat server, this is a part of my code that's listen to getListConnected
event and when it triggered it look for all connected clients
in a given namespace, and then for each client I store their 'username' to another array, convert it to JSON response and then send:
socket.on('getListConnected', function(msg){
var clients = namespace.clients();//get all client in that nsp
var usernames = Array() ;//init array
for(i in clients)//for each clients
{
clients[i].get("username", function(value){
usernames.push(value);
});
}
socket.emit('getListConnected',JSON.stringify(usernames));//send
});
The problem with this code is the client.get()
method is asynchronous which means that usernames are sent empty.
How can I wait for usernames until it's filled, or how can I wait for the loop until it's finished?