Given a situation where you have to get data from multiple async functions or promises, what is the best way to collect and persist the data so it can be used after all are complete. An example situation would be multiple database queries which need to get rendered in a single page.
I've come across the below code, which looks like a solid pattern to me, but being new to the async game am unsure.
function complexQuery(objectId) {
var results = {};
return firstQuery.get(objectId).then(function (result1) {
results.result1 = result1;
return secondQuery.find();
})
.then(function (result2) {
results.result2 = result2;
return thirdQuery.find();
})
.then(function (result3) {
results.result3 = result3;
return results;
});
}
complexQuery(objectId)
.then(function (results) {
//can use results.result1, results.result2, results.result3
res.render('dash', results); //example use
});
What is the best way to handle this kind of situation?
Edit for clarification: Must be in series, queries may require information from a preceding promise result.