Reputation: 5092
I find myself often in a situation where I need to query for multiple models in the database before sending them to be rendered in HTML. What I have done is
ModelA.findById({ ... }).then(function(modelA) {
ModelB.findById({ ... }).then(function(modelB) {
return both modelA and modelB
});
});
This has a couple of problems:
ModelA.findById({ ... }).then(function(modelA) {
ModelB.findById({ ... }).then(function(modelB) {
ModelC.findById({ ... }).then(function(modelC) {
ModelD.findById({ ... }).then(function(modelD) {
ModelE.findById({ ... }).then(function(modelE) {
ModelF.findById({ ... }).then(function(modelF) {
return all models
});
});
});
});
});
});
How do I execute the queries simultaneously and continue the page rendering only after all queries have been executed?
Upvotes: 0
Views: 42
Reputation: 5233
You can use Promise.all
in this case, all your queries will be executed simultaneously, but the then
function will be executed when all your queries returned.
var queries = [
ModelA.findById({...}),
ModelB.findById({...}),
ModelC.findById({...}),
ModelD.findById({...}),
ModelE.findById({...}),
ModelF.findById({...})
];
Promise.all(queries).then(function (results) {
console.log(results); // [modelA, modelB ...]
});
You should also read about javascript promises.
Upvotes: 1