Tuesday, 14 July 2020

Cannot store/return mySQL results in a variable outside of the query's callback function

I am trying to write a function that when given the username of the client (which I am storing in cookies), sends a query to the database and returns the user_id of the client who has that username. I want to assign this to a variable that lives outside of the callback function of the query, but I get undefined every time. I have done some reading about how it is an asynchronous process, and have tried to pass in a callback function like some online forums have said. If anybody knows how to fix this that would be great, thanks in advance.I write the functions here:function getUserId(username, callback){db.query('SELECT user_id FROM users WHERE username = ?', [username], function(err, results){callback(results);});};function returnUserId(res){//this logs the user idconsole.log(res[0].user_id);//this comes back as undefinedreturn(res[0].user_id);};And call it here://this logs the username which means req.cookies.currentUser is the right thing to pass inconsole.log(req.cookies.currentUser);var currentUserId = getUserId(req.cookies.currentUser, returnUserId);//this spits out undefinedconsole.log(currentUserId);​

Submitted July 15, 2020 at 02:16AM by snowchoux

No comments:

Post a Comment