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 accomplish the desired effect.
All of these functions can run in parallel, I just need to know when all are done.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With