0

This is a bit of a mystery for me. I have two functions:

1)

var revisionNumber;
var $list = $('<ul>');

TFS_Wit_WebApi.getClient().getWorkItem(284)
    .then(function(query) {
        revisionNumber = query.rev;
    });

2)

for (i = 0; i < revisionNumber; i++) {
    TFS_Wit_WebApi.getClient().getRevision(284, 6)
        .then(function(query) {
            $list.append($('<li>').text("story board" + revisionNumber));
        });
}

The reivisonNumber value is supposed to be 15. When in for loop I put instead of the variable a number 15, the second function works just fine as well as for loop and it actually displays this number 15.

If I remove for loop, it also works and displays the value of revisionNumber variable from the first function.

However, when I put revisionNumber in my for loop, the second function does not work at all.

Why is it not going inside the second function with the above for loop?

Student
  • 155
  • 1
  • 2
  • 10
  • 4
    It's unclear what you're asking as well. It may well be http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call, though, if your `for` loop immediately follows the code in (1) above and you're expecting `revisionNumber` to have a value other than `undefined` in it when that loop starts. – T.J. Crowder Jul 19 '16 at 14:30
  • Infamous loop + async return. Jackpot! – Yury Tarabanko Jul 19 '16 at 14:31
  • @T.J.Crowder So yes, that for loop follows the code in (1). I checked that value by removing the for loop and the value was not undefined in the second function. – Student Jul 19 '16 at 14:38
  • @T.J.Crowder that answer was ruthless :D +1 – Dellirium Jul 19 '16 at 14:39

1 Answers1

0

The for loop is probably being executed before the getWorkItem().then() callback is being executed. You will need to wait for that callback to run before running the for loop, either by moving it into the callback function, or putting it in it's own function and calling that function in the callback.

For example:

var revisionNumber;
var $list = $('<ul>');

TFS_Wit_WebApi.getClient().getWorkItem(284).then(function (query) {
     revisionNumber = query.rev;
     for (i = 0; i < revisionNumber; i++) {
         TFS_Wit_WebApi.getClient().getRevision(284, 6).then(function (query) {
             $list.append($('<li>').text("story board" + revisionNumber));
         });
     }
});
Will
  • 2,163
  • 1
  • 22
  • 22