title: Writing a login in node.js using express
body: <p>I'm writing a login for a website in node.js using the express framework. However, the code is executing in a weird order and I'm not sure how to fix it. Here's a simplified version of the relevant code:</p>
  
  <pre><code>app.post('/login', function(req, res){
      var login_error;
      if (!req.session.username) { //if no one is logged in
          if (req.body.user != undefined &amp;&amp; req.body.pass != undefined) {
              client.query('USE data', function(error, results) {}
          });
          client.query('SELECT id FROM user WHERE username=? AND password=?',[reg.body.user, req.body.pass],
          function(err, results,fields) {
              if (err || results.length == 0) {
                  login_error=1;
                  console.log('a '+login_error); //LINE A
              }
          });
      }
      console.log('b '+login_error);  //LINE B
      if (login_error == undefined) {
          req.session.username=req.body.user;
      }
      client.end();
  }
  res.render('login', {
      user: req.session.username,
      login_error: login_error
  });
  </code></pre>
  
  <p>The page is always rendering with login_error=undefined, even when the username/pass combo is not in the database. In this case LINE A is printing login_error=1, but LINE B is printing login_error=undefined. Furthermore LINE B prints before LINE A even though it appears later. I'm not really sure what's going on here.</p>