Philippe Rathé
Philippe Rathé

Reputation: 9098

Having a callback after two asynchronous queries have completed using 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
  });
});

Upvotes: 4

Views: 3591

Answers (2)

CrazyCrow
CrazyCrow

Reputation: 4235

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

Upvotes: 12

Chris
Chris

Reputation: 1251

I think you want to look at something like

https://github.com/creationix/step

Upvotes: 1

Related Questions