如何在循环中的promise中处理数据?

时间:2015-08-07 09:43:28

标签: javascript angularjs angular-promise

这是我的方式:

var activeArr = [];
var activeDate = [];
var day = (endDate - startDate) / (24 * 60 * 60 * 1000);
for (var i = 1; i < day + 1; i++) {
    activeDate.push(endDate - (24 * 60 * 60 * 1000) * i);

    var start = endDate - (24 * 60 * 60 * 1000) * i;
    var end = endDate - (24 * 60 * 60 * 1000) * (i - 1);

    statisService.getRegStatis(start, end).then(function(data) {
        activeArr.push(data);
        if(activeArr.length == day){
            var active = [];
            for(var j=0;j<activeArr.length;j++){
                var obj = {};
                obj.date = activeDate[j];
                obj.data = activeArr[j].data;
                active.push(obj);
            }
            $scope.active = active;
        }
    });
}

服务:

userServiceModule.factory('statisService', ['$http', 'serverUrl', function($http, serverUrl) {
return {
    getRegStatis: function(startDate, endDate) {
        var url = serverUrl + "/adminDA/dbReport?startTime=" + startDate + "&endTime=" + endDate;
        return $http.get(url).then(function(result) {
            return result.data;
        });
    }
};

我想将日期和数据放入一个对象中,以便我可以在视图中使用它:

<tr ng-repeat="item in active track by $index">

for循环不会等待所有服务调用完成,所以我在for循环中处理数据,我认为这不是一个好方法,但我不知道如何做得更好。

1 个答案:

答案 0 :(得分:2)

您应该使用延迟API 中的 $ q.defer()承诺管理器。

$ q.defer()获取2种方法:

  • resolve(value):通过给她最终值来解决我们的相关承诺

  • 拒绝(原因):解决了承诺错误。

此外 $ q.all()将promises数组作为参数,并解析所有这些。

<强>控制器

(function(){

function Controller($scope, Service, $q) {

  var promises = [];

  var defer = $q.defer();

  //Process loop
  for (var i = 0; i < 20; ++i){
    //Fill my promises array with the promise that Service.post(i) return
    promises.push(Service.post(i));
  }

  //Resolve all promise into the promises array
  $q.all(promises).then(function(response){
    //Create arr by maping each data field of the response
    var arr = response.map(function(elm){
      return elm.data;
    });
    //Resolve my data when she is processed
    defer.resolve(arr);
  });

  //When the data is set, i can get it
  defer.promise.then(function(data){
    //Here data is an array
    console.log(data)
  });

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

<强>服务

(function(){

  function Service($http){


    function post(num){
      //Just an example, I've pass an object, and just return it then
      return $http.post('path_to_url', {id:num});
    }

    var factory = {
      post: post
    };

    return factory;

  }

  angular
    .module('app')
    .factory('Service', Service);

})();