Reputation: 57
I have several problems with return of queries.
Here, what I would like to do :
//If the email hasn't a good format
if(email_not_good_format())
//I do something
else if(email_already_exists_in_mysql(email))
//I do something
function email_already_exists_in_mysql(email){
connection.query('SELECT COUNT(*) AS nb FROM user WHERE emailUser = ' + connection.escape(email), function(err, rows, fields) {
if (err) throw err;
if(rows[0].nb == 0)
return false;
else
return true;
});
}
I saw on different posts callback function but it doesn't work for what I want to do.
Upvotes: 0
Views: 133
Reputation: 113896
I saw on different posts callback function but it doesn't work for what I want to do.
Yes it does, you just need to change the way you think about code. Instead of writing email_already_exists_in_mysql
you should instead write a function called if_email_already_exists_in_mysql
:
/* Executes callback if email
* already exists in mysql:
*/
function if_email_already_exists_in_mysql (email,callback) {
connection.query(
'SELECT COUNT(*) AS nb FROM user WHERE emailUser = ' +
connection.escape(email),
function(err, rows, fields) {
if(rows[0].nb != 0) {
callback();
}
}
)
}
Then instead of writing this:
//If the email hasn't a good format
if(email_not_good_format()) {
//I do something
}
else if(email_already_exists_in_mysql(email)) {
//I do something
}
you write it like this instead:
//If the email hasn't a good format
if(email_not_good_format()) {
//I do something
}
else {if_email_already_exists_in_mysql(email),function(){
//I do something
})}
Now, you may ask yourself, what if there is another else after that? Well, you need to modify the if_email_already_exists_in_mysql
function to behave like and if...else
instead of just and if
:
function if_email_already_exists_in_mysql (email,callback,else_callback) {
connection.query(
'SELECT COUNT(*) AS nb FROM user WHERE emailUser = ' +
connection.escape(email),
function(err, rows, fields) {
if(rows[0].nb != 0) {
callback();
}
else if(else_callback) {
else_callback();
}
}
)
}
so that you can call it like this:
//If the email hasn't a good format
if(email_not_good_format()) {
//I do something
}
else {
if_email_already_exists_in_mysql(email),function(){
//I do something
},
// else
function(){
//I do something else
}
)}
You can write async code to do pretty much anything regular code can do only instead of returning a value you pass in a callback. Remember:
return in synchronous code == passing in callbacks in asynchronous code.
The code structure must therefore be different but as I demonstrated above the logic you want to implement can be exactly the same.
Upvotes: 1