I'm now learning Node.js and creating a web application, but don't know how to render twice on the same .ejs file.
So in the following .ejs file:
<table>
<% rows.forEach(function(ind){ %>
/* map each value of each field to table */
<% }) %>
</table>
<table>
<% rows2.forEach(function(ind){ %>
/* map each value of each field to table */
<% }) %>
</table>
And I want to execute two separate queries and render them to the same .ejs file, but when I tried to, I can't since at the time when I tried to run first query and render it to the above .ejs file I don't have the result from second query which spits out values for the second table (i.e. row2 data). How can I deal with it? Or do I have to make two separate .ejs file and do rendering twice in a nested form? I like to avoid a nested file as best as possible, so if there were any solutions please tell me...
Thanks.
Just wait until both queries are done before you render the result :)
Conceptually:
db.query(QUERY1, function(err, result1) {
db.query(QUERY2, function(err, result2) {
res.render('template', { rows : result1, rows2: result2 });
});
});
Instead of nesting functions like that, you could take a look at async.parallel, which would make the above code look like this:
async.parallel([
function(callback) { db.query(QUERY1, callback) },
function(callback) { db.query(QUERY2, callback) }
], function(err, results) {
res.render('template', { rows : results[0], rows2 : results[1] });
});
The advantage of using async.parallel is that both queries will run parallel to each other, instead of sequentially as in the first example. So the response will (might) be quicker.