对于所有已解决的promise,Angular $ q.all都返回null

时间:2017-11-03 17:55:14

标签: angularjs

In this plunk我有一个$q.all函数可以解决两个承诺。但是,当我在两种情况下使用值解析时,该函数返回null。这段代码出了什么问题?

var app = angular.module('app', []);

app.controller('myCtl', function($scope,$q) {

            var promises = [];

            promises.push(function(){
                var defer = $q.defer();
                var val1 = "aaa";
                defer.resolve(val1);
                return defer.promise;
            });

            promises.push(function(){
                var defer = $q.defer();
                var val2 = "bbb";
                defer.resolve(val2);
                return defer.promise;
            });


            $q.all(promises).then(function(responses) { 
              $scope.responses = responses;
          });
});

1 个答案:

答案 0 :(得分:3)

这样做,

promises.push(function(){
  var defer = $q.defer();
  var val1 = "aaa";
  defer.resolve(val1);
  return defer.promise;
}());

promises.push(function(){
  var defer = $q.defer();
  var val2 = "bbb";
  defer.resolve(val2);
  return defer.promise;
}());

您只定义了这些函数,但必须使用

调用它们
function () {
  // body
}();  <-- note the '()'

确认在plunker工作。