Mongoose a un support intégré pour les promesses qui fournissent un moyen propre d'attendre l'achèvement de plusieurs opérations de requête asynchrone avec Promise.all
:
// Tell Mongoose to use the native Node.js promise library.
mongoose.Promise = global.Promise;
app.post('/init/autocomplete', function(req, res){
var autocomplete = {
companies: [],
offices: []
};
// Call .exec() on each query without a callback to return its promise.
Promise.all([Company.find({}).exec(), Office.find({}).exec()])
.then(results => {
// results is an array of the results of each promise, in order.
autocomplete.companies = results[0].map(c => ({value: c.name}));
autocomplete.offices = results[1].map(o => ({value: o.name}));
res.json(autocomplete);
})
.catch(err => {
throw err; // res.sendStatus(500) might be better here.
});
});