0

I am querying my sqlite3 database to check user details, then once the query has completed it calls a call-back method. Inside the call-back I can access the data just fine, but when I want to make a copy of that data i.e. assign the value to a session variable or a global instance, then it becomes undefined once the call-back has finished. My question here is, how do I avoid this?

var custFuncs                   = require( '../functions' );
var arrRow = []


// process log in.
router.post( '/login', upload.array(), function( req, res )
{
    custFuncs.checkAuthDetails( req.body.uname, req.body.pass, function ( row )
    {
        //req.session.userID = row.id;
        arrRow.push( row.id );
        console.log( arrRow ); // PRINTS OUT [ 1 ] HERE
    } );

    console.log( arrRow ); // PRINTS OUT [] HERE
    res.redirect( '/' );
});

Then in functions.js:

function checkAuthDetails( userName, pass, callback )
{  
    var hashedPass = encrypt( pass );

    db.serialize( function()
    {
        db.get( "SELECT id, uname, pass FROM user WHERE uname = ?", [userName], function( err, row )
        {
            if( (row.id > 0) && (row.pass == hashedPass) )
            {
                callback( row );
            }
        });
    });
}
MikeO
  • 391
  • 4
  • 17
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ben Fortune Feb 23 '16 at 11:02

1 Answers1

0

The reason it's doing this is because they are asynchronous calls. You should see that the one printing the empty array is being called before the one with the user's id in. This is because it reaches this first. When you call costFuncs.checkAuthDetails it moves straight onto the next line of code in that function rather than wait for costFuncs.checkAuthDetail's callback to be called.

Anything you want to do with that data must be done inside the callback once you have it.

StuStirling
  • 15,601
  • 23
  • 93
  • 150