将参数传递给$ q.all回调

时间:2016-01-17 08:43:17

标签: angularjs q

我需要将一些本地参数传递给$ q.all回调

var actions = [];
var jsonFiles = ["a.json","b.json","c.json"];

for(var index=0; index<3; index++){
    actions.push($http.get('content/' + jsonFiles[index]);
}

$q.all(actions).then(function (values) {
    console.log(index) // Need to print current request index
}

电流输出当然是3,3,3
我需要根据响应顺序打印0,1,2(可以是1,0,2或其他组合)

我已经用我的问题创建了一个jsfiddle - http://jsfiddle.net/dorcohen/n30er4ap/

3 个答案:

答案 0 :(得分:2)

如果我理解正确,您应该使用params

  for (var index = 0; index < 3; index++) 
   {
    actions.push($http.get( jsonFiles[index], {params:{"idx": index }}));
   }

然后:

   $q.all(actions).then(function(values) {
     for (var i=0;i<values.length;i++)
       $scope.indexes.push(values[i].config.params.idx); 
    })

Fiddle

答案 1 :(得分:1)

好的,所以它有点矫枉过正,但我​​认为它会起作用

for(var index=0; index<3; index++){
    actions.push($q.all([
       $q.resolve(index),
       $http.get('content/' + jsonFiles[index]);
    ]);
}

答案 2 :(得分:1)

虽然@ Royi的答案是正确的,但如果不适用于&#34;非http&#34;的承诺。

一种适用于承诺类型的好方法是使用anti-pattern创建defered对象作为包装并解析自己的自定义对象。

虽然这是一种反模式,但在某些情况下你想像这里一样使用它。

HTML:

<div ng-app="app">
  <div ng-controller="ctrl">
    <button ng-click="do()">
      Click
    </button>
  </div>
</div>

JS:

angular.module('app', []).
controller('ctrl', function($scope, $http, $q) {
  $scope.do = function() {
    var acts = [];

    for (var i = 0; i < 3; i++) {
      var defer = $q.defer(); // create your own deferred object

     // worked with a dummy promise - you can use what ever promise you want
      var promise = $q.when({
        obj: i
      });


      promise.then(
        // closure for the current deferred obj + index since we are in a loop
        function(d,idx) {
          return function(item) {
            d.resolve({res: item, index:idx}); // resolve my deferred object when I want and create a complex object with the index and the "real response"
          }
        }(defer,i));

      acts.push(defer.promise);
    }
    $q.all(acts).then(function(res) {
      console.log(res);
    });
  }
});

JSFIDDLE