How can I delay the execution of a function until the other two have finished using $ q?

I am using AngularJS $ q implementation.

Given 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 know that I can delay the execution of another function as follows:

os.doTask1()
    .then(function () {
        doTask3();
});

I would like to start with doTask1 and doTask2 at the same time. Is there a way I can do this and still delay execution so that doTask3 () will not execute until doTask1 and doTask2 succeed.

+3
source share
1 answer

$q.all- this is what you are looking for. ( Documentation )

$q.all promises, , , , , promises . promises, , promises:

$q.all([doTask1(), doTask2()]).then(function(results) {
  // results[0] == result of doTask1
  // results[1] == result of doTask2
  doTask3();
});

-, , , , , :

$q.all({one: doTask1(), two: doTask2()}).then(function(results) {
  // results.one == result of doTask1
  // results.two == result of doTask1
  doTask3();
});

- (, then, , , ), :

var bothPromises = $q.all([doTask1(), doTask2()]);

var task3Promise = bothPromises.then(function(results) {
  var result1 = results[0];
  var result2 = results[1];
  return doTask3(result1, result2);
});

task3Promise.then(function(resultOfDoTask3) { ... });

, - promises, $q.all, , . . Angular $q.


() , , : CoffeeScript, , promises ' .

:

$q.all([doTask1(), doTask2()]).then ([result1, result2]) ->
  # ...

$q.all(one: doTask1(), two: doTask2()).then ({one, two}) ->
  # note that you have to use the same key names
  # as in the object you passed to `$q.all`
+6

All Articles