Node.js – 打破callback函数并在父函数中返回true / false

我正在使用Node Express框架来构buildAPI,并遇到有关基本身份validationfunction的问题。 我需要运行SQL查询来检索有关用户的信息并validation他们的凭据。 查询完成后发生该问题。 SQL数据被发送到一个callback函数,如下所示。 我想要在callback中进行所有的validation,但是我想跳出SQLcallback从express.basicAuth()函数返回true / false。 我已经尝试设置一个全局variables,然后在SQLcallback之外访问它,但是有时查询可能没有完成,直到获取访问该全局variables的块为止。 在此先感谢您的帮助。

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)); }); 

express.basicAuth也支持asynchronous操作:

 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); }); });