AngularJS 1.0.7: Nesting parallel promises with $r

2020-05-05 07:19发布

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();

1条回答
放我归山
2楼-- · 2020-05-05 08:03

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();
查看更多
登录 后发表回答