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

All we need is an easy explanation of the problem, so here it is.

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

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

})();

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply