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 从回调返回值
基础教程推荐
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 在多列上分布任意行 2021-01-01
