3

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.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm now reading a document on async.parallel but it sounds a great fit. Thanks.
I didn't go deeply into reading the document, but when I tried, the argument variable results returned list of list, which consisted of rows and fields. So I changed rows: result[0] to rows: result[0][0] and got what I expected.
@user2360798 ah right, I forgot that node-mysql calls the callback with two arguments instead of just one :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.