【问题标题】:Node.js - Break out of callback function and return true/false in the parent functonNode.js - 跳出回调函数并在父函数中返回真/假
【发布时间】: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


【解决方案1】:

express.basicAuth也支持异步操作:

var auth = express.basicAuth(function(user, pass, next) { 
  ...
  client.query(query, function (err, rows, fields) { 
    if (err)
      next(err);
    else
    if (/* authentication successful */)
      next(null, user); // <-- sets 'req.remoteUser' to the username
    else
      next(null, false);
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多