How to deal the data when the promise in a loop?

2020-08-08 04:32发布

问题:

This is my way:

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;
        }
    });
}

the service:

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;
        });
    }
};

I want to put the date and the data into one object so that I can use it in the view like this:

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

The for loop will not wait for all the service calls to be completed,So I deal the data in the for loop,and I think this is not a good way,but I don't know how to do it better.

回答1:

You should use the $q.defer() promise manager, from the deferred API.

$q.defer() get 2 methods :

  • resolve(value) : which resolve our associated promise, by giving her the final value

  • reject(reason) : which resolve an promise error.

Moreover $q.all() take an promises array as parameter, and resolve all of them.

Controller

(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);

})();

Service

(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);

})();