一尘不染

返回函数Javascript

node.js

我在返回查询时遇到了几个问题。

在这里,我想做的是:

//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;
    });
}

我在不同的帖子上看到了回调函数,但是它不适用于我想做的事情。


阅读 237

收藏
2020-07-07

共1个答案

一尘不染

我在不同的帖子上看到了回调函数,但是它不适用于我想做的事情。

是的,您只需要更改对代码的思考方式即可。与其编写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函数使其行为类似于和if...else而不是just和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
    }
)}

您可以编写异步代码来执行常规代码只能执行的几乎所有工作,而不是返回在回调中传递的值。记得:

返回 同步代码== 以异步代码传递 回调

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

2020-07-07