4

My question is quite similar to the question here: How to pass a value to an AngularJS $http success callback

According to Angular.js

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.

So how would one, do the similar just with .then?

My code is fragmented with something like this in my service

fetchFromAPI: function(key) {
    return $http.jsonp(...); 
}

And this as my controller

for (var i = 0; i < units.length; i++){
    Service.fetchFromAPI(i)
    .then(function(response) {
        console.log(i);
    }, function(response) {
        console.log(response);
    });
}

But the output from the console is the same number due to the for-loop finishing execution before any of the calls is returned and I can't wrap my head around to write the above similar to the .success example, all my attempts gives me an error that my controller is not a function.

The solution posted by Jim Horng is

$http.get('/plugin/' + key + '/js').success((function(key) {
     return function(data) {
        console.log(key, data);
    }
})(key));
Community
  • 1
  • 1
Carsten Farving
  • 541
  • 4
  • 12

2 Answers2

5

Just use built in angular.forEach

angular.forEach(units, function(unit, index){
    Service.fetchFromAPI(unit)
    .then(function(response) {
        console.log(unit, response);
    }, function(response) {
        console.log(response);
    });
}

Docs

Carsten Farving
  • 541
  • 4
  • 12
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
  • My issue is not to iterate over the objects in the array, but rather use the index within the callback function, but that might have been unclear. – Carsten Farving Aug 24 '15 at 13:40
  • After reading through maxdec's link, I realize that the angular.forEach provides the neccesary enclosure to make this work. And it will indeed provide a cleaner code. – Carsten Farving Aug 25 '15 at 06:20
1

One quick solution could be:

for (var i = 0; i < units.length; i++){
  Service.fetchFromAPI(i)
  .then((function(key) {
    return function (response) {
      console.log(key, response);
    };
  })(i), function(response) {
    console.log(response);
  });
}
maxdec
  • 5,707
  • 2
  • 30
  • 35
  • This seems like it solves the issue. I think my issue was the missing return inside the .then(). Will this return conflict with chaining? – Carsten Farving Aug 24 '15 at 13:41
  • @CarstenFarving: the problem has to do with closures inside a for-loop. There's a very good and extensive explanation here: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – maxdec Aug 24 '15 at 13:53