0

I am using a loop to update data to the server and once the response from the server is received it is updated in my local db.But before completing all the updates in local db the promise gets resolved and only one data gets updated. can anyone tell me why the promise gets resolved before completing all the process inside a for loop?

function updatecategories (data, categoryname) {
  var defer = $q.defer();
  var proms = [];
  var prom;
  $log.log('Change in daybook change got called', data);
  $log.log('Change in daybook change got called', categoryname);
  for (var i = 0; i < data.length; i++) {
    delete data[i].is_synced;
    data[i].category = categoryname;
    save(data[i]).then(function (result) {
      $log.log('values changed in daybook', result);
      proms.push('success');//only one data is getting synced to server rest is not by nid on 10-10
    }, function (err) {
      $log.log('error in update to daybook', err);
    });
  }
  $q.all(proms).then(function () {
    defer.resolve('success');
  });
  return defer.promise;
}
Nidhin Kumar
  • 3,278
  • 9
  • 40
  • 72
  • Also https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Suraj Rao Oct 11 '17 at 07:10
  • The for loop will finish first. By then i is data.length and probably only the last promise gets resolved. So as shown below, you want to push the promises themselves to the array instead of the promise result. – Shilly Oct 11 '17 at 07:18
  • why are you waiting for `proms` to complete? There is nothing in it that should resolve, and you are filling it asynchronic, you should rather push the save statement in it to wait for – Icepickle Oct 11 '17 at 08:56

1 Answers1

1

First, can you please add console.log(proms.length); before this line: $q.all(proms).then(function () {?

I am guessing it will print 0, because the first time you push anything to the proms array will happen asynchronously, meaning after the interpreter will finish running the updatecategories function.

If this is indeed the case, consider changing it to something the resembles:

proms.push(save(data[i]).then(function (result) {
  $log.log('values changed in daybook', result);
}, function (err) {
  $log.log('error in update to daybook', err);
}));

Then, when you hit the $q.all(proms) line, proms will be an array full of unresolved promises, which $q.all will wait for all of the to resolve, and then the defer.promise will resolve too.

Gilad Artzi
  • 3,034
  • 1
  • 15
  • 23
  • initally proms.length was 0 so i changed the code like what you have mentioned above at that time i could see the proms.length to be 11 but only one data gets updated and then the promise gets closed. – Nidhin Kumar Oct 11 '17 at 07:35