Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Make 2 async queries with node js

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 !

Problem courtesy of: user3198601

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);
    });
}
Solution courtesy of: Ali

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Make 2 async queries with node js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×