0

I am trying to query, foreach id in an array, some data from the MySQL database. My for loop looks like the following

for(var i = 0; i < res.length; i++) {
    var steamid = res[i].steamid;
    db.query('SELECT `name` FROM `users` WHERE `steamid`=?', [steamid], function(err, rows) {
        var player = {name: rows[i].name};
        team.push(player);
    });
}

But the problem is that the for loop continues before the query is finished and then the var i is already increased by one or two.

Is there a way to check if the query has finished?

Jannis Lehmann
  • 1,428
  • 3
  • 17
  • 31

1 Answers1

2

Just use a closure so that your i refers to the correct index.

function finished(){...}//called when you fetched all your data
var nbDone = 0;
res.forEach(function(elem, i){
    var steamid = elem.steamid;
    db.query('SELECT `name` FROM `users` WHERE `steamid`=?', [steamid], function(err, rows) {
        var player = {name: rows[i].name};
        team.push(player);
        nbDone++;
        if(nbDone == res.length){
          finished();//you know all of your queries have completed
        }
    });
});

you may want to have a look at promises or async in order to handle your asynchronous flows

Community
  • 1
  • 1
grodzi
  • 5,633
  • 1
  • 15
  • 15