Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7185221
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T18:22:08+00:00 2026-05-28T18:22:08+00:00

I’m writing a login for a website in node.js using the express framework. However,

  • 0

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:

app.post('/login', function(req, res){
    var login_error;
    if (!req.session.username) { //if no one is logged in
        if (req.body.user != undefined && 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
});

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T18:22:09+00:00Added an answer on May 28, 2026 at 6:22 pm

    This is happening because of the way callbacks work. In this code:

        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
            }
        });
    

    the function containing line A is not executed immediately. Instead, client.query returns immediately and execution continues, towards line B.

    Then when the select query returns, your callback function executes. So, in order of execution, it will probably come after line B, even though it appears in the source beforehand.

    Consider this example

    client.query('SELECT 1 AS Res', function(err, results) {
      console.log(results.fields.Res);
    });
    
    client.query('SELECT 2 AS Res', function(err, results) {
      console.log(results.fields.Res);
    });
    

    you might well find this producing the following output:

    2
    1
    

    Because the second query might return faster than the first.

    This is the source of Node’s power – the code doesn’t block, it’s asynchronous, so it’s fast.

    To get your example working as intended, you should refactor it to call the code that needs to aware of the results of the query in a separate function. For example something more like this:

    function processLogin(login_error) {
      console.log('b '+login_error);  //LINE B
      if (login_error !== true) {
        req.session.username=req.body.user;
      }
    
      res.render('login', {
          user: req.session.username,
          login_error: login_error
      });
    }
    
    app.post('/login', function(req, res){
        if (!req.session.username) { //if no one is logged in
            if (req.body.user != undefined && 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) {
                    process_login(true);
                } else {
                    process_login(false);
                }
            });
        }
        client.end();
    }
    

    This code won’t work straight away, but notice how I’ve moved the res.render call into a function, which I’m calling from the callback of client.query. Now, you’ll need to allow that callback to access the res variable, either by making it global (which is fine if you’re inside a dedicated ‘login’ module, but otherwise a bad idea), or by passing it to the function as an argument, which might be preferable.

    Just because a line of code appears after another, doesn’t necessarily mean it will be executed after it, if there’s a callback involved. Something which acts similarly which you might be familiar with is timeouts; consider this:

    setTimeout(function() {
      console.log(1);
    }, 1000);
    console.log(2);
    

    In this case, it should be obvious that you’ll see the following:

    2
    1
    

    It’s exactly the same with callbacks to things like mysql queries. Instead of the entire process waiting for client.query to return, execution continues and you put everything that relies on the results from client.query into a callback which you send to client.query.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I used javascript for loading a picture on my website depending on which small
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.