[英]Node.js - Waiting for multiple functions to complete
所以我的代碼看起來像:
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的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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.