0

Hi all i have created a basic nodesjs server using express. There is a login page on which a user is sent, it checks entry from the Sqlite3 DB. My query is Callback function works only after its parent function is done. However in the following case, since the db.each command from the Db takes some time, callback function doesn't give the desired output. But if I set a timeout function it gives an appropriate answer.

Code snipped /*post request userLogin page is called */

app.post('/userLogin',function(req,res){
   checkLogin(req,function(){//using a callback
   setTimeout(function(){//delaying the execution of this part**
   if(userLoginStatus=='SUCCESS'){res.render('userLogin');}
   else{res.send('Wrong credentials');}
   },100);
  });
});


function checkLogin(req,callback){
   db.serialize(function(){
   db.each("SELECT * from USERLOGIN where USERID ='"+req.body.userId+"'"+ 
   " AND PASSWORD='"+req.body.password+"'",function(err,row){
   if(row.USERID.length>0){userLoginStatus ='SUCCESS';}
   else {userLoginStatus = 'UNSUCCESFUL';}
   });
  });
  callback();
}
  • Most likely you will need to chain those calls inside each other. You should read about Javascript asynchronous calls with callbacks. It will be interesting to read about promises, too :-) – flob Jul 27 '17 at 12:09

1 Answers1

0

You need to put your callback in the callback of the db.each function, so it runs AFTER you got the data from your database:

function checkLogin(req, callback) {
    db.serialize(function () {
        db.each("SELECT * from USERLOGIN where USERID ='" + req.body.userId + "'" +
            " AND PASSWORD='" + req.body.password + "'",
            // This is the db.each callback function
            function (err, row) {
                if (row.USERID.length > 0) {
                    userLoginStatus = 'SUCCESS';
                }
                else {
                    userLoginStatus = 'UNSUCCESFUL';
                }
                // you need to call your callback INSIDE of the db.each callback
                callback();
            });
        // Placing it here is wrong, because it will be executed before db.each is completed
        // callback();
    });
}
Danmoreng
  • 2,367
  • 1
  • 19
  • 32
  • It is true that a callback is one way to solve it, but the value should not be passed using a global variable (`userLoginStatus`) but as second argument of the callback. – t.niese Jul 27 '17 at 13:57
  • @t.niese that wasn't part of the question, and he might need the global variable somewhere else. – Danmoreng Jul 27 '17 at 13:58
  • Thanks Danmoreng, it worked for me. Should have been careful with the placement of callback. – Durgesh Pareva Jul 29 '17 at 09:04