Angularjs, wait for a nested promise
Asked Answered
M

2

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
});
Mizzen answered 31/7, 2014 at 18:7 Comment(0)
E
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
});
Encaustic answered 31/7, 2014 at 18:11 Comment(4)
Ok, so maybe I miss something. Isn't $q.all already satisfied when I enter in promise2.then?Mizzen
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.Encaustic
@ryeballarhow to test it? imagine it's Jasmine & Angular test. Could you please update your answer?Engler
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.Kiln
H
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.

Hasan answered 31/7, 2014 at 18:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.