I want to render results from multiple queries to my template from NodeJS.
connection.query("select * from table1",function(err,rows){
if(!err) {
var data1 = JSON.parse(JSON.stringify(rows));
var data2 = fetchDataFromOtherTable(connection); //returns rows from another table
console.log(data2); //prints undefined
res.render('template-page',{data1:data1,data2:data2});
}
});
This behaviour is obvious due to the async nature of javascript, and can be solved if I pass data1 to 'fetchDataFromOtherTable' and then render from that function :
fetchDataFromOtherTable(res,data1,connection);
/*In fetchDataFromOtherTable */
data2 = JSON.parse(JSON.stringify(rows));
res.render('template-page',{data1:data1,data2:data2});
However, for multiple queries, this technique will involve cumulative passing of returned 'rows' at each function call (Also, a lot of function redirects).
Is there a better way to achieve this?