3

i am pretty new to java script and nodejs. i am trying to write a code that checks if an email is already exists in the database, and if not send an error. the problem is that before the database function is ending, my code going to the next line, resulting in undefined variable(emailExists)

this is my code for the sign Up:

app.post('/signUpWeb', function (req, res) {
  var reqBody = req.body;
  var email= reqBody.email;
  var password= reqBody.password;
  var fullName= reqBody.fullName;
  var webDbInsertion  = {email: email, password: password, fullName: fullName};

  var emailExists= DButils.checkIfPKexists(connection, "webusersMail", "email", webDbInsertion.email);

  if(emailExists == false){
    DButils.insertInfoToDB(connection, "webusersMail" ,webDbInsertion);
    console.log("successfull signup");
    res.send("successfull signup");
  }else{
    console.log("signup failed, email: " + email + " allready exits");
    res.send("signup failed");
  }
  res.end();
});

and this is for my database call

  exports.checkIfPKexists=  function(dbConnection, tableName, PK, newPK){
    var query = dbConnection.query('select count(*) as mailPkCount from ' +tableName+ ' where ' +PK+ ' = ?', newPK, function (err, row, result) {   
    if (err) {
      console.error(err);
      return;
    }
    var count= row[0].mailPkCount;
    var bool = (count > 0);
    return bool;
    });
  };
Dan The Man
  • 1,835
  • 6
  • 30
  • 50
  • 1
    When using js and node many api calls are async and _return_ their result either by using callbacks or Promises. You can't return a value from an async call in the way you try it. [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321) – t.niese Nov 15 '15 at 21:26

1 Answers1

0

Well you see, node.JS is designed to be async, while what you're asking isn't impossible, it would shut down the main thread that runs the event loop for that instance of your server.

What I suggest doing is adding a callback function to your "checkIfPKexists" function, and return with the result as a parameter, much like you do in the DBConnection.query. You would then move all the code that isn't getting initialized into your callback.

Edit: Heres a quick code example, polish it up to your liking http://pastebin.com/bEHp4bi2

Sean_A91
  • 333
  • 4
  • 15