【问题标题】:Node.js - Waiting for multiple functions to completeNode.js - 等待多个功能完成
【发布时间】:2012-01-05 23:12:32
【问题描述】:

所以我的代码看起来像:

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();

我研究了 Async 库,当我需要同时运行一定数量的函数时,我将其用于并行处理。但我不确定如何达到预期的效果。

所有这些功能都可以并行运行,我只需要知道什么时候完成。

【问题讨论】:

  • 我不确定你是否正在寻找一个像样的库,但如果你只需要一些琐碎的东西,你可以有一个计数器:最初将其设置为 Object.keys(data).length,然后将其递减.save 回调 - 当它到达 0 时,运行 some_function()
  • @pimvdb 可以工作(这正是我的想法),但是它只是一个启动和运行的小技巧,要获得正确的方法,需要一些 pub/子消息系统(不要让事件和回调过于混乱)

标签: javascript node.js asynchronous


【解决方案1】:

这是Async's forEach方法的完美案例,它将对数组元素执行并行任务,然后调用回调,例如:

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
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2020-08-14
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多