0

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

在这里,我想做的是:

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

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

4

1 回答 1

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函数以使其行为类似于 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
    }
)}

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

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

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

于 2013-07-23T12:52:47.160 回答