Q.all () to resolve multiple mongoose requests at once

I am trying to use the q promises library to run two mongoose requests at the same time. I want to make two queries myself and then execute a function using the results after both queries have completed.

I tried to set up q.all () this way, but the result is always pending in then()

. I need to resolve 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 pending promises object below, not the value. How can I get the values ​​returned from MongoDB for these queries?

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

      

function(err){}

is never executed.

+3


source to share


2 answers


AFAIK, q.all()

only handles arrays of promises, not promises objects (like you are passing through). Also, since Mongoose .exec()

returns promises already, you don't need to wrap them with q(...)

(although it won't hurt if you do).

Try the following:



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

q.all(promises).then(...);

      

+5


source


An alternative usage q

for newer versions of Node is to use the built-in method Promise.all

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

      

+2


source







All Articles