pro.mean pro.mean - 1 month ago 6
AngularJS Question

chained promise in for loop doesn't execute properly

I have chainable promises which are working fine in a single series but now i want to call this serios of chain inside for loop but it does not work as expected.

see my demo plunker and see the output in console.

below is the structure of my chaining promises . I want all publicIP which is returned by

funTwo
; but I want to complete
funThree()
and then want to get all publicIP. As I know that
$q.when()
makes a value in promise object.

but you can see that
console.log('pA', promiseArray);
executed very before and
console.log('res three');
and why
successHandler
and
finally
called before that?

Here surely I am missing something , may be have to write a
return;
in proper place , kindly help me how to executed all function in for loop and return a data array after that for loop ends which can be retried in
successHandler


MyService.funZero()
.then(function(response) {
console.log(response);
var promiseArray = [];
for(var i = 0; i < 2 ; i++) {
console.log('I', i);
MyService.funOne()
.then(MyService.funTwo)
.then(function(res2) {
console.log('res two', res2);
publicIP = res2.ip;
console.log('i', publicIP);
promiseArray.push({'ip': publicIP});
return MyService.funThree(publicIP);
})
.then(function() {
console.log('res three');
})
} // for loop ends
console.log('pA', promiseArray);
return $q.when(promiseArray);
})
.then(function(res4){
console.log('after for loop', res4);
})
.then(successHandler)
.catch(errorHandler)
.finally(final, notify);

Answer

So, I'm not sure exactly what MyService.funThree does, but you can aggregate an array via ipArray.push({'ip': publicIP}) and return that to the MyService.funThree and then the subsequent function. The issue here is there is no guarantee of order in the ipArray if that's what you're looking for. Here's the middle section of that function:

ipArray = [];
for(var i = 0; i < 2 ; i++) {
  console.log('I', i);
  var promise = MyService.funOne()
    .then(MyService.funTwo)
    .then(function(res2) {
      console.log('res two', res2);
      publicIP = res2.ip;
      console.log('i', publicIP);
      ipArray.push({'ip': publicIP});
      return ipArray;
    })
    .then(MyService.funThree)
    .then(function() {
      console.log('res three');
    });

  promiseArray.push(promise);
}
console.log('pA', promiseArray);
return $q.all(promiseArray);
Comments