Student Student - 4 months ago 12
Javascript Question

Value is not being passed to for loop

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?

Answer

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));
         });
     }
});
Comments