gpt4 book ai didi

javascript - 返回函数 JavaScript

转载 作者:行者123 更新时间:2023-11-29 13:43:10 24 4
gpt4 key购买 nike

我在返回查询时遇到了一些问题。

在这里,我想做的事情:

//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.

是的,您只需要改变您思考代码的方式即可。您应该编写一个名为 if_email_already_exists_in_mysql 的函数,而不是编写 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 函数,使其行为类似于 and if...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
}
)}

您可以编写异步代码来执行几乎任何常规代码只能执行的操作,而不是返回在回调中传递的值。请记住:

同步代码中的返回 == 在异步代码中传入回调

因此,代码结构必须不同,但正如我上面演示的,您想要实现的逻辑可以完全相同。

关于javascript - 返回函数 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17808651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com