Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 966
steampowered Avatar asked Dec 24 '22 17:12

steampowered


2 Answers

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(...);
like image 94
robertklep Avatar answered Jan 06 '23 11:01

robertklep


An alternative to using q on newer releases of Node is to use the native Promise.all method with mongoose's mpromise:

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

Promise.all(promises).then(function(results) {
    console.log(results);
}).catch(function(err){
    console.log(err);
});
like image 42
Jason Cust Avatar answered Jan 06 '23 13:01

Jason Cust