Wait for promises inside of a angular.forEach loop

2019-06-03 05:41发布

问题:

I know this has been asked quite a few times already but after a day of search I still don't get it to work, although it's just like what is shown as a solution everywhere...

I have a async request to a database which returns an array of data. For each object in this array I need to start another async request to the database and as soon as ALL of these async requests resolve, I want to return them. I read you could do it with $q.all(...)

So here's the code:

Factory.firstAsyncRequest(id).then(function (arrayWithObjects) {
var promises = [];
var dataArr = [];
  angular.forEach(arrayWithObjects, function (object, key) {
     var deferred = $q.defer();
     promises.push(deferred);
     Factory.otherAsyncRequest(key).then(function (objectData) {
        dataArr.push({
           name: objectData.name,
           key: key,
           status: objectData.status
        });
        deferred.resolve();
        console.info('Object ' + key + ' resolved');
     });
  });
  $q.all(promises).then(function () {
     $rootScope.data = dataArr;
     console.info('All resolved');
  });});

From the console I see that the $q.all is resolved BEFORE each object. Did I get something wrong? This seems to work for everyone...

Your help is highly appreciated, been looking the whole night, it's 5:30am now lol..

Cheers

EDIT: So for anyone who's coming here later: It was just the promises.push(deferred.PROMISE) bit. Tho, I read that anguar.forEach is actually not a recommended method to loop through array because it was originally not constructed to be used by the end-user. Don't know if that's correct but I figured out another way if you don't want to use angular.forEach:

Users.getAll(uid).then(function (users) {
          var uids = ObjHandler.getKeys(users); //own function just iterating through Object.keys and pushing them to the array
          var cntr = 0;
          function next() {
            if (cntr < uids.length) {
              Users.getProfile(uids[cntr]).then(function (profile) {
                var Profile = {
                  name: profile.name,
                  key: uids[cntr],
                  status: profile.status
                });
                dataArr[uids[cntr]] = Profile;
                if(cntr===uids.length-1) {
                  defer.resolve(); 
                  console.info('Service: query finished');
                } else {cntr++;next}
              });
            }
          }
          next();
        });

And the getKey function:

.factory('ObjHandler', [
function () {
  return {
    getKeys: function(obj) {
      var r = [];
      for (var k in obj) {
        if (!obj.hasOwnProperty(k))
          continue;
        r.push(k)
      }
      return r
    }
  };
}])

回答1:

Instead of

promises.push(deferred);

Try this:

promises.push(deferred.promise);