AngularJS 1.0.7: Nesting parallel promises with $resources

this post extends a previous one already solved. Please see it, to get in context: Nesting promises with $resources in AngularJS 1.0.7

With that approach in mind, I would like to make a parallel call to functions and when both are completed then run the searchBoats function with the results. I think I can nest the promises, but I also think it can be done in parallel, maybe with $q.all. Unfortunately, this promises topic is confusing for me and I don´t know how to do it.

Taking the previous post example, I would like to do something like:

var parseURL = function() {
  var deferred = $q.defer();
  var promise = deferred.promise;
  promise.then(function success(result) {
    console.log(result);
    searchBoats(result);
  });

  // Instead of resolve when parseBoatType promise is returned, I would like to   
  // wait for two promises
  parseBoatType().then(deferred.resolve);
  parseDestination().then(deferred.resolve);
  // of course, with this code deferred will be resolved when first promise 
  // comes. Is it possible to use $q.all here?
};
parseURL();

Answers:

Answer

As in your earlier question, there is no need to use a deferred here. Just use $q.all(), which returns a promise:

var parseURL = function() {
  $q.all([parseBoatType(), parseDestination()])
      .then(function (results) {
          console.log(results);
          searchBoats(results);
      });
};
parseURL();

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.