我有这样的代码:

      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(){...

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

最佳答案

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

09-25 17:21
查看更多