最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js - Waiting for multiple functions to complete - Stack Overflow

programmeradmin0浏览0评论

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 acplish the desired effect.

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

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 acplish the desired effect.

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

Share Improve this question asked Jan 5, 2012 at 14:27 Quinton PikeQuinton Pike 3,8618 gold badges34 silver badges37 bronze badges 2
  • I'm not sure if you're looking for a decent library, but if you only need something trivial, you can just have a counter: set it to Object.keys(data).length initially, and decrement it the .save callback - when it has reached 0, run some_function(). – pimvdb Commented Jan 5, 2012 at 14:40
  • @pimvdb that would work ( it was exactly what i was thinking of ), however it's just a small hack to get up and running, to get the correct way of doing it one would need some pub/sub messaging system ( not to get too messy with events and callbacks ) – Poelinca Dorin Commented Jan 5, 2012 at 14:52
Add a ment  | 

1 Answer 1

Reset to default 8

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
});
发布评论

评论列表(0)

  1. 暂无评论