我可以在AngularJS中使用$ q.all并使用不返回.promise的函数吗?

Sam*_*tar 3 javascript promise angularjs

如果我有以下功能:

   doTask1: function ($scope) {
       var defer = $q.defer();
       $http.get('/abc')
           .success(function (data) {
               defer.resolve();
           })
           .error(function () {
               defer.reject();
           });
       return defer.promise;
   },

   doTask2: function ($scope) {
       var defer = $q.defer(); 
       var x = 99;
       return defer.promise;
   },
Run Code Online (Sandbox Code Playgroud)

我被告知我可以等待这两个承诺:

    $q.all([
            doTask1($scope),
            doTask2($scope)
    ])
        .then(function (results) {

        });
Run Code Online (Sandbox Code Playgroud)

如果任务2没有返回承诺怎么样?我在AngularJS的$ q文档中看到有"when".但是我不知道如何使用它并且没有例子.

是不是我必须让doTask2通过两行来返回一个承诺:

var defer = q.defer()
return defer.promise
Run Code Online (Sandbox Code Playgroud)

或者有更简单的方法吗?

Ste*_*wie 6

$ q.when用于您不知道函数是返回promise还是直接值的情况.

下面的示例/ plunker显示了一个方法,其结果在$ q.all中使用,并且每次调用时都返回不同类型的对象(int或promise):

PLUNKER

app.controller('MainController', function($scope, $q, $http) {
  var count = 0;

  function doTask1() {
    var defer = $q.defer();
    $http.get('abc.json')
      .success(function (data) {
        defer.resolve(data);
      })
      .error(function () {
        defer.reject();
      });

    return defer.promise;
  }

  /**
   * This method will return different type of object 
   * every time it's called. Just an example of an unknown method result.
   **/
  function doTask2() {
    count++;
    var x = 99;
    if(count % 2){
      console.log('Returning', x);
      return x;
    } else {
      var defer = $q.defer();
      defer.resolve(x);
      console.log('Returning', defer.promise);
      return defer.promise;
    }

  }

  $scope.fetchData = function(){

    // At this point we don't know if doTask2 is returning 99 or promise.
    // Hence we wrap it in $q.when because $q.all expects 
    // all array members to be promises
    $q.all([
      $q.when(doTask1()),
      $q.when(doTask2())
    ])
      .then(function(results){
        $scope.results = results;
      });

  };

});
Run Code Online (Sandbox Code Playgroud)
<body ng-app="myApp" ng-controller='MainController'>
  <button ng-click="fetchData()">Run</button>
  <pre>{{results|json}}</pre>
</body>
Run Code Online (Sandbox Code Playgroud)