Lazy
Lazy

Reputation: 1837

Node.Js Async usage

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()
        })

    })
})
}

Upvotes: 0

Views: 41

Answers (1)

lwang135
lwang135

Reputation: 572

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();
    })
  })
}

Upvotes: 1

Related Questions