Node.js – 等待多个函数来完成

所以我有这样的代码:

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

我已经看了asynchronous库,我用于并行时,我有一个function,我需要运行一次的设置数量。 但是我不确定如何达到预期的效果。

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

对于Async的forEach方法来说,这是一个完美的例子,它将对数组元素执行并行任务,然后调用callback函数,例如:

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