My Process1() function has a database loop, so Process2() and Process3() calling more than once. Which function should I use in async, to wait for a for loop?
async.waterfall([
function(callback){
Process1(yyy, function(){
//process1 function has a for loop.
callback();
})
},
function(callback){
Process2(function(){
// so process2() is calling more than once
callback();
})
}
], function (callback) {
Process3()
});
Process1() :
function Process1(yyy, pass){
user.find({}).exec(function(e, users){
_.each(users, function(_user){
user.findOneAndUpdate(
{'_id' : user_id},
{$inc : {'xxx' : yyy}},
function(e){
!e && pass()
})
})
})
}
asked Dec 3, 2014 at 19:12
Lazy
1,8374 gold badges29 silver badges52 bronze badges
1 Answer 1
Looking at your code, Process2 will definitely be called more than once, because lodash and underscore does not wait until the call back happens. They are just utilities methods.
To solve asynchronous situations like this, just use async.each or async.eachSeries.
function Process1(yyy, pass){
user.find({}).exec(function(e, users){
async.each(users, function(_user, next){
user.findOneAndUpdate(
{'_id' : user_id},
{$inc : {'xxx' : yyy}},
function(e){
!e && next()
})
}, function(err) {
pass();
})
})
}
answered Dec 3, 2014 at 19:27
lwang135
5721 gold badge3 silver badges14 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Lazy
Thank you so much, I've understood the async usage thanks to you.
lang-js
forloop. It has to.process2. Aren't there any solution? @Brad thanks.Process2won't run untilcallbackin the first closure is called.forloop do? Is it a series of DB calls? If not, then you can put the async to the db process.