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 acplish the desired effect.
All of these functions can run in parallel, I just need to know when all are done.
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 acplish the desired effect.
All of these functions can run in parallel, I just need to know when all are done.
Share Improve this question asked Jan 5, 2012 at 14:27 Quinton PikeQuinton Pike 3,8618 gold badges34 silver badges37 bronze badges 2-
I'm not sure if you're looking for a decent library, but if you only need something trivial, you can just have a counter: set it to
Object.keys(data).length
initially, and decrement it the.save
callback - when it has reached0
, runsome_function()
. – pimvdb Commented Jan 5, 2012 at 14:40 - @pimvdb that would work ( it was exactly what i was thinking of ), however it's just a small hack to get up and running, to get the correct way of doing it one would need some pub/sub messaging system ( not to get too messy with events and callbacks ) – Poelinca Dorin Commented Jan 5, 2012 at 14:52
1 Answer
Reset to default 8This 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
});