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

十年热恋 提交于 2019-12-04 20:56:14

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

})();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!