nodeJS return value from callback(nodeJS 从回调返回值)
问题描述
我正在构建一个应用程序,在该应用程序中,在进行特定调用时,我必须阻止并等待身份验证查询的结果,然后才能继续.
I am building an application in which on a particular call, i must block and wait for the results from an authentication query before coninuing.
function authenticate(userid, hash)
{
mysql_client.query("SELECT `hash` FROM `auth` WHERE `userid` = " + userid, function selectCb(err, results, fields) {
if (err)
{
client.send("Error communicating with mysql, please retry your request");
return false;
}
if(results.length == 0 || results[0].hash != hash)
{
client.send("Error comparing authentication data with database, please retry request");
return false;
}
return true;
}
);
}
我希望能够从 authenticate() 函数本身返回这些值,而不是从内部匿名函数 selectCb 返回这些值,并且在回调完成之前具有身份验证块.我该怎么做?
I want to be able to return those values from the authenticate() function itself, not the internal anonymous function selectCb and have authenticate block until the callback is complete. How can I go about doing this?
推荐答案
你的外部函数需要提供一个回调本身,一旦 mysql 调用完成就可以执行它.类似的东西:
Your outer function needs to provide a callback itself which can be executed once the mysql call is done. Something along the lines of this:
function authenticate(user, pass, callback) {
mysql_client.query("...", function (err, results, fields) {
if (err) {
callback("Error communicating ...");
} else if (results.length ...) {
callback("Error comparing authentication...");
}
callback()
});
});
示例用法:
authenticate('jim', '123456', function (err) {
if (err) {
alert(err);
} else {
alert('Welcome');
}
});
这篇关于nodeJS 从回调返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:nodeJS 从回调返回值


- SQL 临时表问题 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01