9

I have 3 services that return 3 promises, but the third needs the data from the second, so I call it inside the second. I want to wait for all the three promises to be solved, this is the way that I implemented, but doesn't work (waits only for the first and the second).

var promise1, promise2, promise3;

promise1 = service1();
promise2 = service2();

promise2.then(function (data) {
  promise3= service3(data);

});

$q.all([ promise1, promise2, promise3]).then(function success() {
 //somehing
});
Tres
  • 571
  • 1
  • 5
  • 19

2 Answers2

18

You can assign the second promise's then() callback with a returned promise from the third service.

var promise1, promise2, promise3;

promise1 = service1();
promise2 = service2();

promise3 = promise2.then(function (data) {
  return service3(data);
});

$q.all([ promise1, promise2, promise3]).then(function success() {
 //somehing
});
ryeballar
  • 29,658
  • 10
  • 65
  • 74
  • Ok, so maybe I miss something. Isn't $q.all already satisfied when I enter in promise2.then? – Tres Jul 31 '14 at 18:17
  • 1
    No, since it waits for promise3 to get resolved. It is mentioned in the AngularJS $q documentation that the `.then()` function will `return a new promise`. – ryeballar Jul 31 '14 at 18:21
  • @ryeballarhow to test it? imagine it's Jasmine & Angular test. Could you please update your answer? – Anton Dozortsev Nov 30 '17 at 10:37
  • I'd just like to add that in my situation, where I had even further nested promises, I found some success by adding the nested promises to the existing promise array variable used by the first `$q.all()` and adding a second `$q.all()` in the `.then()` of the first. (Followed by another `.then()` with the stuff I wanted to wait to do!) This waited again with the new promises. You could repeat this for further layers, but perhaps already we're in the territory of bad design. – Ross Llewallyn Apr 17 '19 at 04:21
0

Have you tried to nest your promise 2 inside promise 1, and then put your final resolve inside the promise 3 delegate?

That's pretty slick code and I'm certainly no expert, but have had to wait to accomplish things on other service calls and have had to do things like that.

Joe
  • 340
  • 3
  • 9