Qui*_*ike 5 javascript asynchronous 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();
Run Code Online (Sandbox Code Playgroud)
我已经查看了异步库,当我有一定数量的函数需要在一次运行时,我用它来并行.但我不确定如何达到预期的效果.
所有这些功能都可以并行运行,我只需要知道什么时候完成.
这是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
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3357 次 |
最近记录: |