gpt4 book ai didi

javascript - Node JS 回调

转载 作者:太空宇宙 更新时间:2023-11-04 02:58:29 24 4
gpt4 key购买 nike

在理解回调时遇到一些困难,这是我的身份验证代码(通过 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 语句不起作用?

最佳答案

简单地执行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 代码时,您将看到使用此技术。

关于javascript - Node JS 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23690952/

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