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.
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(...);
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With