4

How to make foreach loop synchronous in AngularJS

var articles = arg;

articles.forEach(function(data){
      var promises = [fetchImg(data), fetchUser(data)];

      $q.all(promises).then(function (res) {
           finalData.push(res[1]);
      });
});

return finalData;

I want finalData array to be returned only after the forEach loop gets over. Is there any way to chain it with promises? Something that will execute the foreach loop first and then return the array after the loop is over?

Community
  • 1
  • 1
foxtrot3009
  • 149
  • 2
  • 6

2 Answers2

4

Chaining promises from a foreach loop

Promises are chained by returning values (or a promise) to the handler function in the .then method. Multiple promises are consolidated by using $q.all which itself returns a chainable promise.

function fetchUsers(arg) {
    var articles = arg;

    var promises = articles.map(function(a){
        var subPromises = [fetchImg(a), fetchUser(a)];        
        return $q.all(subPromises).then(function (res) {
             //return for chaining
             return {img: res[0], user: res[1]};
        });
    });

    //consolidate promises    
    var finalPromise = $q.all(promises); 
    return finalPromise;
};

Because calling the .then method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain.1

The returned promise will either resolve fulfilled with an array of users or will resolve rejected with the first error. Final resolution is retrieved with the promise's .then and .catch methods.

 fetchUsers(args)
     .then ( function onFulfilled(objArray) {
          $scope.users = objArray.map(x => x.user);
          return objArray;
     }).catch ( function onRejected(response) {
          console.log("ERROR: ", response);
          throw response
     })
 ;

The $q.defer Anti-pattern

The problem with using $q.defer() is that it breaks the promise chain, loses error information, and can create memory leaks when errors are not handled properly. For more information on that see, AngularJS Is this a “Deferred Antipattern”?.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • I assume with this line `var p = $q.all(promises).then(function (res) {` promises should actually be `subPromises` or am I missing something? – Ian G Sep 27 '18 at 16:47
3

You can modify your code like this:

function fetArticles(arg) {
    var articles = arg;
    var promises = [], finalData = [];
    var deferred = $q.defer();

    articles.forEach(function(data) {
          var userPromise = fetchUser(data);
          userPromise.then(function (res) {
               finalData.push(res[1]);
          });

          promises.push(fetchImg(data));
          promises.push(userPrommise);
    });

    $q.all(promises).then(function() {
         deferred.resolve({finalData: finalData, foo: "bar"});
    });

    return deferred.promise;
}

Now, call this method and register a final callback:

fetArticles(arg).then(function(data) {
     console.log("finalData: ", data.finalData, data.foo === "bar");
});
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • var promises = [fetchImg(data), fetchUser(data)]; means that after image data and userdata is fetched, it should be inserted into articles data and res[1] means the final data from fetchUser(data) i.e. from promises array[1] position. – foxtrot3009 Mar 27 '16 at 10:03
  • See [Is this a “Deferred Antipattern”?](https://stackoverflow.com/questions/30750207/is-this-a-deferred-antipattern). The answer as written will hang the `$q.defer` if any of the server requests fail. – georgeawg Jan 12 '19 at 05:26