user5303752
user5303752

Reputation:

Parse promises with loop

I have code this code

userQuery.find().then(function(users){

 users.forEach(function(user){

 //some query and promises  with the user object.

  });

 }).then(function(){
    //func2

 })  

the func2 will run when the query on all the users finish or when the loop finish?

I want to run a function when all the query that in the loop will finish How can I do this?

Thanks

Upvotes: 0

Views: 502

Answers (2)

vineet kumar
vineet kumar

Reputation: 1

var lastFun = null ;

userQuery.find().then(function(users){

   users.forEach(function(user){
     if (lastFun !== null)
        lastfun();//it will be your last function
     else 
        lastFun = true;
   });

}).then(function(){
   if (lastFun === true){
       //call your function here because this is now last function
   } else {
       lastfun = function (){};
   }
});  

Upvotes: 0

Shanoor
Shanoor

Reputation: 13662

You'll have to store the promises you have in the forEach in an array and return a promise for func2, something like this:

userQuery.find().then(function(users){
    var promises = [];
    users.forEach(function(user){
        //some query and promises  with the user object.
        var promise = user.doSomethingAsync()
            .then(function anotherThing() {

            });
        promises.push(promise);
    });

    return Promise.all(promises);
}).then(function(){
    //func2
})

I used Promise.all in the example but I don't know what lib you're using.

Upvotes: 1

Related Questions