簡體   English   中英

我可以在AngularJS中使用$ q.all並使用不返回.promise的函數嗎?

[英]Can I use $q.all in AngularJS with a function that does not return a .promise?

如果我有以下功能:

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

我被告知我可以等待這兩個承諾:

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

        });

如果任務2沒有返回承諾怎么樣? 我在AngularJS的$ q文檔中看到有“when”。 但是我不知道如何使用它並且沒有例子。

是不是我必須讓doTask2通過兩行來返回一個承諾:

var defer = q.defer()
return defer.promise

或者有更簡單的方法嗎?

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

  };

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

有沒有更簡單的方法來做到這一點[比手動構建和解決延期並返回承諾]?

是的,使用$q.when函數

doTask2: function ($scope) {
    return $q.when( 99 );
},

但是,您實際上並不需要這樣做。 $q.all將 - 雖然未在文檔中聲明 - 也可以使用非承諾值(實現調用 _ref轉換它)。 所以就

return 99;

很好。 但是,如果您事先知道它是同步的,那么使用promises似乎沒有多大意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM