我在不同的帖子上看到了回调函数,但它不适用于我想做的事情。
是的,你只需要改变你对代码的看法。email_already_exists_in_mysql
您应该编写一个名为的函数,而不是编写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();
}
}
)
}
然后,而不是这样写:
//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
}
你可以这样写:
//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
})}
现在,你可能会问自己,如果在那之后还有另一个呢?好吧,您需要修改if_email_already_exists_in_mysql
函数以使其行为类似于 andif...else
而不仅仅是 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();
}
}
)
}
这样你就可以这样称呼它:
//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
}
)}
您可以编写异步代码来执行几乎所有常规代码只能执行的操作,而不是返回您在回调中传递的值。记住:
在同步代码中返回== 在异步代码中传入回调。
因此,代码结构必须不同,但正如我在上面演示的那样,您要实现的逻辑可以完全相同。