nodeJS从回调返回值 [英] 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从回调返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文