Ameya Pandya
Ameya Pandya

Reputation: 1

Node.js Asynchronous Callback Function Not Working As Reqiured

I am trying to design a registration page in node.js using Knex.js and mysql. Here is the code:

Registration Page `

router.post('/', function(req, res, next){
    var fname = req.body.fname;
    var mname = req.body.mname;
    var lname = req.body.lname;
    var email = req.body.email;
    var uname = req.body.uname;
    var pwd = req.body.password;
    var conf_pwd = req.body.conf_password;
    var tnc = req.body.tnc; 
    var errors = req.validationErrors();

    //Validation
    req.checkBody('fname', 'The First Name is Required').notEmpty();
    req.checkBody('mname', 'The Middle Name is Required').notEmpty();
    req.checkBody('lname', 'The Last Name is Required').notEmpty();
    req.checkBody('uname', 'The Username is Required').notEmpty();
    req.checkBody('email', 'The Email is Required').notEmpty();

    var rand = Math.floor(Math.random()*90000) + 10000;

    //hash The password
    var hashpassword = crypto.createHash('sha512').update(pwd).digest('hex');
    var IdVal = email+uname;
    var IdHash = crypto.createHash('sha512').update(IdVal).digest('hex');
    var tstamp = new Date().toString();
    //Add The User
    if(errors){
        res.render('register', {
            errors: errors
        });
    }else{

        var newUser = ({
            Id: IdHash,
            FirstName: fname,
            MiddleName: mname,
            LastName: lname,
            Email: email,
            UserName: uname,
            HashPassword: hashpassword,
            ActivationCode: rand.toString(),
            ActivationStatus : false,
        });
        User.CheckUser(uname, function(stat){
            console.log('Stat : ',stat);
            if(stat == 1){
                res.render('register', {
                    uerrors: "The Username Already Exists"
                    });
            }else if(stat == 2)
            {
                res.render('register', {
                    uerrors: "Error Occured"
                    });
            }
            else if(stat == 0){ 
                User.CreateUser(newUser, function(err){
                    if (err){ throw err}
                    else{
                        res.render('register', {
                            message: "Verification Email Sent Please Check Email"
                        });
                    }
                });
            }
        });
    }   
});

So What i Wanted to do is check if username exists. If not then create the new user and then show that user is created. And Here is the Code in User.js

module.exports.CheckUser  = function(uname, callback){
    knex('Clients')
        .where({UserName: uname})
        .select()
        .then(function(result){
            if(!result || !result[0]){
                console.log('User Not Found');
                callback(0);
            }else{
                if(result[0].UserName == uname){
                    callback(1);
                }
            }
        })
        .catch(function (err){
            console.log(err);
            callback(2);
        });
}
module.exports.CreateUser = function(newUser, callback){
    knex('Clients')
        .insert(newUser)
        .catch(function (err){
            callback(err);
        });
}

Here, what exactly is happening that the functions in user.js are getting executed first and then it is showing that the username already exists. But the username is just created.

Here is the output of the code,

GET /register 304 670.944 ms - -
GET /bootstrap/css/bootstrap.min.css 304 9.677 ms - -
GET /dist/css/AdminLTE.min.css 304 7.780 ms - -
GET /plugins/iCheck/square/blue.css 304 7.291 ms - -
GET /plugins/jQuery/jQuery-2.2.0.min.js 304 2.312 ms - -
GET /bootstrap/js/bootstrap.min.js 304 2.259 ms - -
GET /plugins/iCheck/icheck.min.js 304 2.076 ms - -
GET /bootstrap/fonts/glyphicons-halflings-regular.woff2 304 0.468 ms - -
GET /plugins/iCheck/square/blue.png 304 0.439 ms - -
{ method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ 'q' ],
  __knexQueryUid: '99707783-2767-4c37-ae4c-0bd31f98427d',
  sql: 'select * from `Clients` where `UserName` = ?' }
User Not Found
Stat :  0
{ method: 'insert',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings:
   [ '41040',
     false,
     '[email protected]',
     'q',
     '2e96772232487fb3a058d58f2c310023e07e4017c94d56cc5fae4b54b44605f42a75b0b1f358991f8c6cbe9b68b64e5b2a09d0ad23fcac07ee9a9198a745e1d5',
     '70b32fc5adc4d2fa6ad5a40d9b6bfe4acc745d0c9c71d47a8266a4d54868198acb29644dc6133fb51cd682dcf1fc72a52278a51ade397ed7f2a38f8ec809e0bf',
     'q',
     'q',
     'q' ],
  __knexQueryUid: 'dee0340f-c247-4608-a29e-da984cc13e49',
  sql: 'insert into `Clients` (`ActivationCode`, `ActivationStatus`, `Email`, `FirstName`, `HashPassword`, `Id`, `LastName`, `MiddleName`, `UserName`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)' }
POST /register - - ms - -
{ method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ 'q' ],
  __knexQueryUid: 'a58fe912-3a9e-4af0-85ca-e1ba2aa9559b',
  sql: 'select * from `Clients` where `UserName` = ?' }
Stat :  1
POST /register 200 105.596 ms - 3234

Upvotes: 0

Views: 149

Answers (1)

tokeryberg
tokeryberg

Reputation: 191

Your output shows that the user does not exist. CheckUser prints 'User Not Found' and calls callback(0). stat equals 0 which is why a new user is created by the following code.

else if(stat == 0){ 
   User.CreateUser(newUser, function(err){
     if (err){ throw err}
       else{
         res.render('register', {
           message: "Verification Email Sent Please Check Email"
         });
       }
     });
}

Upvotes: 1

Related Questions