[英]Node.Js Async usage
My Process1()
function has a database loop, so Process2()
and Process3()
calling more than once. 我的
Process1()
函数具有数据库循环,因此Process2()
和Process3()
调用不止一次。 Which function should I use in async
, to wait for a for loop
? 我应该在
async
使用哪个函数来等待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() : 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()
})
})
})
}
Looking at your code, Process2
will definitely be called more than once, because lodash
and underscore
does not wait until the call back happens. 看你的代码,
Process2
肯定会被调用一次以上,因为lodash
和underscore
不会等待回调发生。 They are just utilities methods. 它们只是实用程序方法。
To solve asynchronous
situations like this, just use async.each
or async.eachSeries
. 要解决此类
asynchronous
情况,只需使用async.each
或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();
})
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.