mardi 22 mars 2016

Problems with function callbacks in a for loop

I have a function that runs a for loop and then callback the results of the for loop after it is finished. My issue is that in this for loop function I have 2 functions back to back that have callbacks and they take about half a second for them both to finish (maybe less). When I make the call with proper data, my result array is called back after it is finished, however while the usernames are unique, the pictures are Identical which is not what I want. I believe this has something to do with JS trying to be asynchronous but It just is breaking. Here is my code:

function forCallback(rows, callback){
  var done = 0;
  for(i = 0 ;i < rows.length; i++){
    var steamid = rows[i].steamid;
    userinfo.getUserName(steamid, function(name){
        userinfo.getUserPicture(steamid, function(picture){
        results.push({
          name: name,
          picture: picture
        })
        done++;
        console.log("Queried " + done + " username(s)")
        if(done == (rows.length)){
          callback(results);
        }
      });
   });
  }
}

The function takes in sql rows and parses the data that way if you were wondering. Any help is appreciated, THANKS so much!!!



Problems with function callbacks in a for loop

Aucun commentaire:

Enregistrer un commentaire