Passing variable to promise in a loop

One way is to capture i in a closure :

for(var i in superarray) {
    (function(i) {
        MyService.get(superarray[i].externalID).then(function(r) {
            console.debug(i);
        });
    })(i);
}

Another way would be to arrange for itemID to be repeated back as a property of r :

for(var i in superarray){
    MyService.get(superarray[i].externalID).then(function(r) {
        console.debug(r.itemID);
    });
};

Leave a Comment