Search code examples
javascriptmongooseq

q.all() to resolve multiple mongoose queries concurrently


I am trying to use the q promise library to run two mongoose queries concurrently. I wish to make the two queries independently, then execute a function using the results after both queries are complete.

I attempted to set up q.all() this way, but the result is always state pending in the then(). I need resolved query results instead of pending promises.

var q = require('q');

var promises = {
    aircraft: q(aircraftModel.findOne({_id: tailNumber})
        .exec()),
    faaAircraft: q(faaAircraftModel.findOne({_id: tailNumber.substring(1)})
        .exec())
};

q.all(promises).then(function(result){
    console.log(result)
}, function(err){
    console.log(err)
})

The result is the object of pending promises below, not values. How can I get values returned from MongoDB for these queries?

{ aircraft: { state: 'pending' },
  faaAircraft: { state: 'pending' } }

The function(err){} is never executed.


Solution

  • AFAIK, q.all() only handles arrays of promises, not objects of promises (like you're passing). Also, since Mongoose's .exec() returns a promise already, you don't have to wrap them using q(...) (although it doesn't hurt if you do).

    Try this:

    var promises = [
      aircraftModel.findOne({_id: tailNumber}).exec(),
      faaAircraftModel.findOne({_id: tailNumber.substring(1)}).exec()
    ];
    
    q.all(promises).then(...);