Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable to promise in a loop

I have a promise in a loop, and I don't know how to pass some scope variables into the promise handler.

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

MyService is a working service, with a get method that return a promise.

app.factory('MyService', function($http,$q) {   return {      get : function(itemID){         var deferred = $q.defer();         $http.get('/someresturl/'+itemID).then(function(e) {                  deferred.resolve(e.data);         }, function(reason) {                 deferred.reject(reason);         });         return deferred.promise;     } }); 

In my console, the console.debug logicaly doesn't display 1,2,3,4,5. But 5,5,5,5,5. (there are 5 elements in my superarray).

How can I pass 'i' value in my promise scope, so I can use it in the then() ?

Is it possible?

like image 740
Ant Avatar asked Jun 21 '13 21:06

Ant


2 Answers

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);     }); }; 
like image 52
Beetroot-Beetroot Avatar answered Sep 30 '22 08:09

Beetroot-Beetroot


By the time your callback is run, i will refer to the last element in your array. You can use a closure and capture the current value of i:

for (var i in superarray){     (function(j) {         MyService.get(superarray[j].externalID).then(function(r) {             console.debug(j);         });     })(i); } 
like image 21
Blender Avatar answered Sep 30 '22 08:09

Blender