Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js - Waiting for multiple functions to complete

Node.js - Waiting for multiple functions to complete

Problem

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.

Problem courtesy of: Quinton Pike

Solution

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
});
Solution courtesy of: alessioalex

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js - Waiting for multiple functions to complete

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×