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

If I have the following functions:

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

I was told that I can wait for both promises as follows:

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

        });

How about if task 2 does not return a promise? I saw in the $ q documentation for AngularJS there is an "when". However, I do not understand how to use it and there is no example.

This is so that I MUST have doTask2, returning a promise, having two lines:

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

or is there an easier way to do this? ll

+3
source share
2 answers

$ q.when is used in scenarios where you do not know in advance whether the function returns a promise or a direct value.

/plunker , $q.all (int ) , :

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 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>
+6

[ ]?

, $q.when :

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

. $q.all - - ( _ref, ).

return 99;

. , , , promises, , .

+4

All Articles