1
for (var i = 0; i < data.length; i++) {
    var childId = data[i].child_id;
    fetchElementDetails(
        childId,
        childTableNameByParentTableName(tableName), 
        function (d) {
            for (var j = 0; j < d.extraVariables.length; j++) {
                if (endsWith(d.extraVariables[j].name, "_id")) {
                    var selector = $("td[data-childId="+childId+"]")
                        .filter("[data-type=" + d.extraVariables[j].name + "]");
                    selector.empty();
                    selector.append(d.extraVariables[j].value);
                }   
            }
        }
    );
}

The function fetchElementDetails() makes an ajax call and takes some time to complete, by that time the for statement continues and the variable childId changes value. How can I make the for statement wait for the function fetchElementDetails() to finish and then go to the next iteration?

I'm a newbie in javascript so any comments are wellcome, I'm looking for the best practice because I get these kind of (synchronization) problems all the time. Fire away!

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
  • 7
    Classic closure problem. http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue – elclanrs Aug 06 '14 at 03:12

1 Answers1

0

As pointed out in the question comments, this is a general issue with closures - if you're learning JavaScript, understanding it is worth your time :)

The simplest fix is to bind i within a function scope inside the for loop:

for (var i = 0; i < data.length; i++) {
    (function(i) {
      var childId = data[i].child_id;
      // ...
    })(i);
}
candu
  • 2,827
  • 23
  • 18