title: synchronous mysql queries in nodejs
body: <p>I'm pretty new to nodejs and I'm having some difficulties to understand how to use the mysql connection object.</p>
  
  <p>My problem is not in the code but in the design pattern.</p>
  
  <p>lets say I have a user module</p>
  
  <pre><code>module.exports = function(){
      return{
          id: "",
          load: function(id){
              var sql = 'SELECT * from users where id = '+ DB.escape(id);
              console.log(1);
              DB.query(sql, function (err, rows) {
                  this.id = rows[0].id; // not working
                  console.log(rows[0].id); // prints the id 4
                  console.log(2);
              });
              console.log(3);
          }
      }
  }
  </code></pre>
  
  <p>from outside the module i run the next code</p>
  
  <pre><code>var user = require('../modules/user');
  var selected_user = user();
  console.log("entering users me route");
  selected_user.load(4);
  console.log("user id is " + selected_user.id); //This does not print the id 4
  </code></pre>
  
  <p>when I run the code, the console logs 1, then 3, and then 2.
  This is due to the asynchronous flow of node js.</p>
  
  <p>But if I'm building a website, and I need the query to end in order to populate my user object before I send the HTML to the browser???</p>
  
  <p>What's the right way to do it ?</p>
  
  <p>Also when I try to populate the id property of user in the id i receive from the DB it does not work.</p>
  
  <p>Any ideas?</p>
  
  <p>Thanks</p>