emil f.
emil f.

Reputation: 93

Sending multiple query results to res.render() using node-mysql and mysql-queue

I [new to node.js and programming in general] have two mysql query results (member info and list of workshops that members can attend) and need to send them to res.render() to be presented in .jade template (Member edit page).

To do this I'm using node-mysql and mysql-queue modules. Problem is I don't know how to pass callback function to render the response before queue.execute() finishes so I made workaround and put first two queries in the queue (mysql-queue feature), executed the queue, and afterwards added third "dummy query" which has callback function that renders the template.

My question is can I use this workaround and what would be the proper way to this using this modules?

exports.memberEdit = function (req, res) {

    var q = connection.createQueue();

    var membersResults,
        htmlDateSigned,
        htmlBirthDate,
        servicesResults;

    q.query("SELECT * FROM members WHERE id= ?;", req.id, function (err, results) {
      console.log("Članovi: " + results[0]);
      membersResults = results[0];
      htmlDateSigned = dater.convertDate(results[0].dateSigned);
      htmlBirthDate = dater.convertDate(results[0].birthDate);
    });

    q.query("SELECT * FROM services", function (err, results) {
      console.log("Services: " + results);
      servicesResults = results;
    });

    q.execute();

    // dummy query that processes response after all queries and callback execute 
   // before execute() statement
    q.query("SELECT 1", function (err,result) {
    res.render('memberEdit', { title: 'Edit member', 
                               query:membersResults, 
                               dateSigned:htmlDateSigned,   
                               birthDate:htmlBirthDate,
                               services:servicesResults }); 
})
};

Upvotes: 1

Views: 2038

Answers (1)

robertklep
robertklep

Reputation: 203484

I think an alternative could be to use a transaction to wrap your queries with:

var trans = connection.startTransaction();
trans.query(...);
trans.query(...);
trans.commit(function(err, info) {
  // here, the queries are done
  res.render(...);
});

commit() will call execute() and it provides a callback which will be called when all query callbacks are done.

This is still a bit of a workaround though, it would make more sense if execute() would provide the option of passing a callback (but it doesn't). Alternatively, you could use a module which provides a Promise implementation, but that's still a workaround.

Upvotes: 1

Related Questions