karoma
karoma

Reputation: 1558

Getting a variable out of a nested function in Node.js

I'm using a function to check if a user is already registered on a site. However I can't figure out how to get the value of rows out of the function selectEmail()

I'm trying to store it within temp, but it seems to store it within its own local version of it, and I'm left with an empty variable once the query part ends.

function checkEmail(email, req, res){
  var temp;
  dbConnect(req,res);
  var query = 'SELECT EMAIL FROM USERS WHERE EMAIL="'+email+'"';
  connection.query(query, function selectEmail(err,rows,fields){
    if (err) {
        throw err;
      }
    temp=rows;
  })
  dbClose(req,res);
  console.log(temp);
  if (temp==""){
      console.log('No matching email in database');
      return 0;
  }
  else{
      console.log('Duplicate Email detected in database');
      return 1;
  }
}

I've heard I'm supposed to use a callback, but I can't figure out how to get that working either.

Upvotes: 0

Views: 1217

Answers (1)

Jeff B
Jeff B

Reputation: 30099

I am guessing that connection.query is asynchronous, meaning that it does not finish before the rest of the code executes. That means that temp does not have a value when you reach if(temp==""){.

To handle this, a callback is used. A callback is a function that is called once the code is complete, which in this case is connection.query(). That is exactly what you have in this case, except not quite formatted correctly:

connection.query(query, function selectEmail(err,rows,fields){
    if (err) {
        throw err;
    }
    temp=rows;
})

Here selectEmail() is the callback, except that callbacks should be provided as function pointers, or anonymous functions (without a name):

connection.query(query, function(err,rows,fields){
    if (err) {
        throw err;
    }
    temp=rows;
});

This code will likely occur well after checkEmail() has returned. Anything you want to happen after conection.query() is complete should be in the callback or called by the callback. Like this:

connection.query(query, function(err,rows,fields){
    if (err) {
        throw err;
    }

    dbClose(req,res);

    if (rows==""){
        console.log('No matching email in database');
        handleEmailCheckFailure();
    }
    else{
        console.log('Duplicate Email detected in database');
        handleEmailCheckSuccess();
    }
});

Of course, you expect checkEmail() to return a value based on whether the check succeeded or not. This will not work with an asynchronous call. You will need to have functions to handle the passing and failing cases (handleEmailCheckFailure, etc above). You also need to be aware that some time will elapse depending on the connection before either of these cases is called.

Upvotes: 3

Related Questions