0

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

    })
})
}
7
  • It will always wait for a for loop. It has to. Commented Dec 3, 2014 at 19:14
  • But I have to run that database process before process2. Aren't there any solution? @Brad thanks. Commented Dec 3, 2014 at 19:16
  • That's what will happen with the code you have shown here. Process2 won't run until callback in the first closure is called. Commented Dec 3, 2014 at 19:18
  • What does your Process1 for loop do? Is it a series of DB calls? If not, then you can put the async to the db process. Commented Dec 3, 2014 at 19:19
  • In my experience this kind of code is easier to express using the promise model, they're a lot easier to chain. Commented Dec 3, 2014 at 19:19

1 Answer 1

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();
    })
  })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, I've understood the async usage thanks to you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.