Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Waiting for multiple functions to complete

So I have code that looks something like:

var data = someobject;

for(var x in data){
    mongo.findOne({ _id:data[x]._id },function(e,post){
        if(post != null){

            post.title = 'omg updated';
            post.save(function(){
                console.log('all done updating');
            });

        }
    });
}

// I need all ^ those functions to be done before continuing to the following function:
some_function();

I have looked into Async library, which I use for parallel when I have a set number of functions I need to run at 1 time. But I am not sure how to accomplish the desired effect.

All of these functions can run in parallel, I just need to know when all are done.

like image 292
Quinton Pike Avatar asked Jan 05 '12 14:01

Quinton Pike


1 Answers

This is a perfect case for Async's forEach method, which will execute parallel tasks on the elements of an array and then invoke a callback, example:

async.forEach(Object.keys(data), function doStuff(x, callback) {
  // access the value of the key with with data[x]
  mongo.findOne({ _id:data[x]._id },function(e, post){
    if(post != null){
      post.title = 'omg updated';
      post.save(callback);
    }
  });  
}, function(err){
  // if any of the saves produced an error, err would equal that error
});
like image 123
alessioalex Avatar answered Oct 03 '22 08:10

alessioalex