Reputation: 646
So I do this:
module.exports.checkEmailInUse = (email) => {
connection.query('SELECT `id` FROM `users` WHERE email = ?',
[
email
],
function(err, rows, fields) {
console.log(rows.length);
if(rows.length > 0){
return true;
}
else{
return false;
}
}
);
}
This table is blank. I get 0 returned as it should. But over in this other file I do this:
if(Database.checkEmailInUse(email)){
callback({success: "false", message: "Email Already In Use"});
return false;
}
This should NOT fire because this returns 0.... but it does.
But now if I return them as strings like:
return "true";
and:
if(Database.checkEmailInUse(email) == "true")
It will work.
This is my first project with NodeJS and am stumped here.
EDIT ANSWER. Thanks qqilihq!! :
module.exports.checkEmailInUse = (email) => {
var queryTheEmail = (email, callback)=>{
connection.query('SELECT `id` FROM `users` WHERE email = ?',
[
email
],
function(err, rows) {
if (err) {
callback(err,null);
}
else{
callback(null,rows);
}
}
);
}
queryTheEmail(email, (err, rows) => {
if (err) {
console.error('SQL error: ', err);
return false;
}
if(rows.length > 0){
return true;
}
else{
return false;
}
});
}
Upvotes: 2
Views: 930
Reputation: 11454
The problem is, your checkEmailInUse
function actually returns nothing. The DB query happens asynchronously: Check the nesting of the functions. As a (simplified) rule of thumb: Asynchronity is viral -- as soon as your code contains asynchronous parts, everything which makes use of it needs to take care of asynchronity as well.
You'll need to refactor this, to either use callbacks or return promises. Following example shows how to do it using callbacks (and some additional code cleanup):
module.exports.checkEmailInUse = (email, callback) => {
connection.query('SELECT `id` FROM `users` WHERE email = ?',
[
email
],
function(err, rows, fields) {
if (err) return callback(err);
callback(null, rows.length > 0);
}
);
}
Then, use the checkEmailInUse
function as follows:
Database.checkEmailInUse(email, function(err, exists) {
if (err) {
return callback({success: "false", message: "Error when checking the DB"});
}
if (exists) {
callback({success: "false", message: "Email Already In Use"});
} else {
callback({success: "true", message: "Come in!"});
}
});
Once, you're getting familiar to the asynchronous concept and your codebase grows, it's worth considering to introduce promises in order to avoid the so called 'callback hell' and make you code much more readable (or use helpers such as async.js).
Either way, this has nothing to do with booleans in particular as the original question title assumed.
Upvotes: 2