0

I have a function that executes three mongooose commands. 1. Finds list of all partners. 2. Finds list of all users. 3. Update users table.

Problem: Mongoose does it asynchronously and it executes other commands. How do I make it execute in series 1,2,3 and then execute other commands. Below, I have attached a code snippet.

The issue with this is it runs the three mongoose commands aynchronously and calls redirect().

router.post('/login', function(req, res, next) {
  Partner.findOne({'groupName': req.session.user.groupnName}), function(error, data) {
    var partnerInfo = data;
    if(partnerInfo && req.session.user)  {
      req.session.user.accountID = partnerInfo.accountID;
      req.session.user.iamRole = partnerInfo.iamRole;
    } 
  };
var id;
 User.find({'username': req.session.user.username}, function(err, data) {
    if(data)  {
      id = data._id;
     } 
  });

User.findByIdAndUpdate(id, req.session.user, function(error) {});
return res.redirect('/home');
});
vtammy
  • 115
  • 2
  • 8
  • Read up on how to use callbacks. Or even promises. Mongoose supports that too. https://docs.nodejitsu.com/articles/getting-started/control-flow/what-are-callbacks/ – Roshan Oct 29 '17 at 05:51
  • Use async.waterfall([fn1, fn2, ...], cb): https://www.npmjs.com/package/async-waterfall – Ramsing Nadeem Oct 30 '17 at 12:27

1 Answers1

0

You should nest the calls in callbacks.

func1(args, function(){
    // do something here
    func2(someMoreArgs, function(){
        // do something more here
        func3(andMore, function(){

        })
    })
})

If you want to avoid nesting callbacks, use the promise interfaces of mongo-client or mongoose

Pubudu Dodangoda
  • 2,742
  • 2
  • 22
  • 38
  • Oh please no. Not the flying V! – Neil Lunn Oct 29 '17 at 05:56
  • @NeilLunn Even I would avoid nesting callbacks. The solution will be to use Promises instead. – Pubudu Dodangoda Oct 29 '17 at 05:58
  • Then don't post such dross if you would not do it yourself. There is no need to when there is an [excellent resource](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) for explaining returning and passing values with the various methods available. Certainly more helpful then "nest callbacks" do you not think? ( Rhetorical question - So don't answer, just think ). – Neil Lunn Oct 29 '17 at 06:00
  • @NeilLunn That is why I have suggested to use Promises at the end of the answer. And if you think from a performance perspective, callbacks are faster than Promises – Pubudu Dodangoda Oct 29 '17 at 06:02