【发布时间】:2013-03-30 20:50:37
【问题描述】:
我正在使用 Node Express 框架构建 API,但遇到了有关基本身份验证功能的问题。我需要运行 SQL 查询来检索有关用户的信息并验证他们的凭据。查询完成后会出现此问题。 SQL 数据被发送到回调函数中,如下所示。我想在该回调中进行所有验证,但我想打破 SQL 回调和从 express.basicAuth() 函数返回 true/false。我尝试设置一个全局变量,然后在 SQL 回调之外访问它,但有时查询可能在它获取访问该全局变量的块时尚未完成。提前感谢您的帮助。
var auth = express.basicAuth(function(user, pass) {
// Query to select information regarding the requested user
/* Query here to find the requested user's data */
client.query(query, function (err, rows, fields) {
if (err) throw err;
GLOBAL.sql = rows;
/* I want to break out of this query callback function and return true from this auth variable */
});
// Sometimes the query isn't completed when it gets to this stage
console.log(JSON.stringify(GLOBAL.sql));
});
【问题讨论】:
-
你需要在回调中执行所有关于
rows的处理。 JavaScript 是非阻塞的,您的console.log应该经常在 SQL 查询完成之前运行。不要使用GLOBAL,继续回调。并以return...语句结束。
标签: javascript mysql node.js callback asynccallback