节点JS回调

时间:2014-05-16 00:48:45

标签: javascript node.js express

在理解回调时遇到一些麻烦,继承我的身份验证代码(通过MySQL)

function authenticate(username, password, callback) {
    var query = "SELECT * from mydb.users where username='" + username + "'and BINARY password='" + password + "'";
    connection.query(query, function (err, rows) {
        if (rows[0] != undefined) {
            if ('username' in rows[0]) {
                if (rows[0].username == username) {
                    callback(true);
                }
            }
        }
        callback(false);
    });
};

exports.assets=function(req,res) {
    var username = req.param("username");
    var password = req.param("password");

    authenticate(username, password, function (didAuthenticate) {
        if (didAuthenticate) {
            console.log("Authenticated");
        }
        else {
            console.log("Failed");
        }
    }); 
};

用户/通行证匹配时的输出:

Authenticated
Failed

没有匹配:

Failed

当didAuthenticate返回true时if / else语句怎么办?

2 个答案:

答案 0 :(得分:4)

简单地执行callback(...)并不会结束函数的执行;你需要一个return语句告诉函数停止运行,如下所示:

function authenticate(username, password, callback) {
    var query = "SELECT * from mydb.users where username='" + username + "'and BINARY password='" + password + "'";
    connection.query(query, function (err, rows) {
        if (rows[0] != undefined) {
            if ('username' in rows[0]) {
                if (rows[0].username == username) {
                    return callback(true);
                }
            }
        }
        return callback(false);
    });
};

当您阅读其他NodeJS代码时,您将看到此技术。

答案 1 :(得分:1)

不是使用return语句来终止,而是可以为你的失败条件设置else语句。

function authenticate(username, password, callback) {
    var query = "SELECT * from mydb.users where username='" + username + "'and BINARY     password='" + password + "'";
    connection.query(query, function (err, rows) {
        if (rows[0] != undefined && rows[0].username === username) {
            callback(true);
        }
        else {
            callback(false);
        }
    });
};