Kangze Huang
Kangze Huang

Reputation: 351

How to synchronously execute FOR LOOP using $q promises?

I have an array of Facebook groupIDs that I want to check in synchronous order, and if one fails, to skip to the next. When they all finish executing, I want to send all the results to my server.

The below code explains the gist of what I want to accomplish (of course it does not work):

var groups = [1111,2222,3333];
var feed_collection = [];

// Unfortunately this for loop does not wait for the FB api calls to finish before looping to next
for(var x = 0; x < groups.length; x++){
   FB.api("/"+groups[x]+"/feed", function(response, err){
      feed_collection += response;
   });
}
// Send the feed_collection to server
feed_collection.sendToServer();

How can I get my for loop to wait? I know I can use $q.all(), however I am stuck on how to generate the promises and save them to a promise_array. This code is on the client-side and I am using AngularJS 1, but I am open to any approach. Mucho gracias!

Upvotes: 0

Views: 575

Answers (1)

Phillip
Phillip

Reputation: 6253

function getGroupFeed(groupId) {
  var deferred = $q.defer();
  FB.api('/' + groupId + '/feed', function (response, err) {
    if (err) return deferred.reject(err);
    return deferred.resolve(response);
  });
  return deferred.promise;
}

That is how you can quickly generate a promise in Angular. Now you can also create an array of promises:

var groupPromises = groups.map(function (groupId) {
  return getGroupFeed(groupId);
});

Or if you insist on a for loop:

var groupPromises = [];
for (var i = 0, len = groups.length; i < len; i++) {
  groupPromises.push(getGroupFeed(group[i]));
}

This array of promises can then be used in $q.all, which is only resolved once all promises in the array are resolved.

Upvotes: 3

Related Questions