AngularJS:forEach http获取数据 - 等待其他方法,直到加载来自循环的所有数据

时间:2015-10-01 14:28:34

标签: javascript angularjs promise

我有这样的代码:

      var commentAuthorIds = [];
      $scope.commentAuthors = [];
      angular.forEach($scope.news.Comments, function(el) {
        if (angular.isDefined(el.AuthorId)){
          commentAuthorIds.push(el.AuthorId);
        }
      });
      commentAuthorIds = $filter('unique')(commentAuthorIds);
      var promises = [];
      angular.forEach(commentAuthorIds, function(el) {
        promises.push($scope.getCommentsAuthorData(el));
      });
      $q.all(promises).then(function(){
        console.log('all data loaded!');
        angular.forEach($scope.news.Comments, function(el) {
          angular.forEach($scope.commentAuthors, function(subEl) {
            if (el.AuthorId === subEl.Id){
              el.Author = response.FirstName + ' ' + response.LastName;
              el.Thumbnail = response.Thumbnail;
            }
          });
        });
      });

      $scope.getCommentsAuthorData = function(userId){
        $http.get('/app/' + $scope.company.Id + '/users/' + userId, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        .success(function(response) {
          $scope.commentAuthors.push(response);
        });
      };

我只需在angular.forEach($scope.news.Comments, function(el) {...加载后调用$q.all(promises).then(function(){...

我做错了什么?我的代码不起作用(

1 个答案:

答案 0 :(得分:2)

getCommentsAuthorData不返回承诺...在$ http

之前添加返回
$scope.getCommentsAuthorData = function(userId){
    return $http.get('/app/' + $scope.company.Id + '/users/' + userId, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
  };

基于此:

  

all函数返回值数组的promise。当这个   承诺得到满足,数组包含了履行的值   原始承诺,与承诺的顺序相同。如果其中之一   如果承诺被拒绝,则返回的承诺立即生效   拒绝,而不是等待批次的其余部分。

这可能是您的问题....所以使用此$ q扩展可以解决此问题add this to your application 然后你可以这样做:

$q.allSettled(promises).then(function(responses){
      angular.forEach(responses,function(response){
            if(response.status!="rejected"){
                 $scope.commentAuthors.push(reponse.value);
            }else{
                 console.log(response.reason);
            }
      });
});