Javascript 如何将值传递给AngularJS$http然后回调

Javascript 如何将值传递给AngularJS$http然后回调,javascript,angularjs,callback,Javascript,Angularjs,Callback,我的问题与这里的问题很相似: 根据Angular.js $http legacy promise方法success和error已被弃用。改用标准then方法 那么,一个人会如何,仅仅对一个人做类似的事情呢 我的代码在我的服务中是碎片化的 fetchFromAPI: function(key) { return $http.jsonp(...); } 这是我的控制器 for (var i = 0; i < units.length; i++){ Service.fetch

我的问题与这里的问题很相似:

根据Angular.js

$http legacy promise方法success和error已被弃用。改用标准then方法

那么,一个人会如何,仅仅对一个人做类似的事情呢

我的代码在我的服务中是碎片化的

fetchFromAPI: function(key) {
    return $http.jsonp(...); 
}
这是我的控制器

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

一个快速解决方案可以是:

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);
  });
}
for(变量i=0;i
只需使用内置的
angular.forEach

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

我的问题不是迭代数组中的对象,而是在回调函数中使用索引,但这可能不清楚。在阅读了maxdec的链接后,我意识到angular.forEach提供了必要的附件来实现这一点。而且它确实会提供一个更干净的代码。这似乎解决了这个问题。我认为我的问题是.then()中缺少返回。这个返回会与链接冲突吗?@CarstenFarving:问题与for循环中的闭包有关。这里有一个非常好和广泛的解释:
angular.forEach(units, function(unit, index){
    Service.fetchFromAPI(unit)
    .then(function(response) {
        console.log(unit, response);
    }, function(response) {
        console.log(response);
    });
}