0

Can anyone tell me what's wrong with this code? When I console.log from within the getUserByEmailQuery function it gives me the user_id however when I return the result it is null. I can't seem to figure out why.

Here's my code:

function getUserByEmailQuery(email, callback) {
  const sql = "select * from users where email = ?;";

  con.query(sql, [email], function (err, result) {
    if (err) throw err;
    console.log("checking id within: " + result[0].user_id); // prints - checking id within: 2
    return callback(result);
  });
}

function getUserByEmail(email) {
  var user = null;

  getUserByEmailQuery(email, (result) => {
    user = result;
  });

  console.log("checking id outside: " + user[0].user_id); // TypeError: Cannot read property '0' of null
}

Any help is greatly appreciated. I can provide the larger context of what I'm doing if necessary.

hello_friend
  • 707
  • 3
  • 9
  • 19
  • 1
    `con.query()` is asynchronous. Move the final log into the callback function and should work fine. Right now you should be seeing the final log print to console first while the query is being done – charlietfl Dec 13 '20 at 06:17
  • @charlietfl thanks that helps. However, how do I get the value out of callback functions? Like if I return user from inside that callback function won't the same thing happen - namely having to use a callback function to access user again? Sorry if this is a stupid question. – hello_friend Dec 13 '20 at 06:34

0 Answers0