Make 2 async queries with node js
Problem
so I want to display a table with all the "room" in my database, I also want to show the creator of the room but only the id of the user is stocked in the room table, so I have to do a query on the user table.
I tried something like this :
socket.on('room', function() {
connection.query('SELECT * FROM room', function(err, rows) {
for(i=0;i" +
"" + room_name + " " +
"" + room_nbPlayer + " " +
"" + room_language + " " +
"" + username + " " +
"");
});
}
});
});
function build_user(id,callback){
connection.query('SELECT username FROM user WHERE id ="'+id+'"', function(err, user) {
var username = user[0].username;
callback(username);
});
}
So, for exemple if I try a
console.log(room_name);
before this function
build_user(rows[i].creator, function(res){
I got all the name, but once I enter in the function the name are all the same, so at the end my table is wrong. It only got the right username of the user, but all the variable from the room query display always the same one (which is the last room in my database)
Thanks you !
Solution
This happens because by the time build_user finishes, your for loop has reached the last item. So your room_name, room_language, etc., are the last item in row. So you can fix it by passing that data across via callbacks.
socket.on('room', function() {
connection.query('SELECT * FROM room', function(err, rows) {
for(i=0;i" +
"" + room_name + " " +
"" + room_nbPlayer + " " +
"" + room_language + " " +
"" + username + " " +
"");
});
}
});
});
function build_user(options,callback){
var id = options.creator;
connection.query('SELECT username FROM user WHERE id ="'+id+'"', function(err, user) {
var username = user[0].username
callback(username, options);
});
}
Discussion
View additional discussion.