0

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!!!

Henry Jeff
  • 57
  • 8

1 Answers1

4

The problem is that your asynchronous functions are capturing a reference to steamid and that value changes as the for loop continues. Instead, you need to capture the value of steamid and make sure that value is local to your callback. You can do this using an IIFE.

for (var i = 0; i < rows.length; i++) {
  (function(steamid) {
    userinfo.getUserName(steamid, function(name) {
      ...
    });
  })(rows[i].steamid);
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91