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 中连接多个表 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
