Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a callback after two asynchronous queries have completed using mongoose

Tags:

mongoose

Using mongoose, I would like having a callback after 2 different queries have completed.

var team = Team.find({name: 'myteam'});
var games = Game.find({visitor: 'myteam'});

Then how to chain and/or wrap those 2 requests within promises assuming I want those requests non blocking and executed asynchronously?

I would like to avoid the following blocking code:

team.first(function (t) {
  games.all(function (g) {
    // Do something with t and g
  });
});
like image 691
Philippe Rathé Avatar asked Dec 12 '22 18:12

Philippe Rathé


1 Answers

I think you already found solution but anyway. You can easily use async library. In this case your code will looks like:

async.parallel(
    {
        team: function(callback){
            Team.find({name: 'myteam'}, function (err, docs) {
                callback(err, docs);
            });
        },
        games: function(callback){
            Games.find({visitor: 'myteam'}, function (err, docs) {
                callback(err, docs);
            });
        },                    
    }, 
    function(e, r){
        // can use r.team and r.games as you wish
    }
);
like image 140
CrazyCrow Avatar answered Jun 17 '23 15:06

CrazyCrow