我有一个带有MySQL查询的检查脚本,问题是授权函数在完成MySQL查询之前执行,所以它总是返回false。怎么解决它?
mysql= require('mysql');
var connection = mysql.createConnection({});
check_auth(req.query.s){
var sql = "query to mysql";
connection.query(sql, function(err, results) {
if (err) throw err;
if (results.length > 0) {
return true;
}else{
return false;
}
}
io.configure(function () {
io.set('authorization', function(req, callback) {
var auth=check_auth(req.query.s);
console.log(auth);
if (auth===true){
return callback(null, true);
}else{
return callback('notauth',false);
}
});
});
编辑:作为Jarema的新结构但仍然无法正常工作
mysql= require('mysql');
var connection = mysql.createConnection({});
function check_auth(input, callback){
var sql = "query to mysql";
connection.query(sql, function(err, results) {
if (err) callback(err);
if (results.length > 0) {
callback(null,results.values);
}else{
callback(null, false);
}
}
io.configure(function () {
io.set('authorization', function(req, callback) {
check_auth(req.query.s, function(err, result) {
if (err) {
//handle that error somehow. we dont not structure of Your func.
return console.log('error:(');
}
if(result === false) {
return callback('notauth', false);
} else {
return callback(null, result);;
}
});
});
});
错误是
TypeError: undefined is not a function
at Query._callback (myserver.js:54:12)
at Query.Sequence.end (node_modules/mysql/lib/protocol/sequences/Sequence.js:78:24)
at Query._handleFinalResultPacket (node_modules/mysql/lib/protocol/sequences/Query.js:143:8)
at Query.EofPacket (node_modules/mysql/lib/protocol/sequences/Query.js:127:8)
at Protocol._parsePacket (node_modules/mysql/lib/protocol/Protocol.js:205:24)
at Parser.write (node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (node_modules/mysql/lib/protocol/Protocol.js:37:16)
at Socket.<anonymous> (node_modules/mysql/lib/Connection.js:73:28)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:746:14)
第54行是
callback(null,results.values);
答案 0 :(得分:1)
如果在调用下一个函数/ if statment时,check_auth查询仍在处理,对我来说这意味着它是异步的。如果它是同步的,它将阻止代码执行直到完成。
编辑:正如Jonatham所提到的,查询函数本身可能是异步的。如果你把它放在'普通'同步函数中,它就意味着你可以将内部异步结果返回到父函数,并从父函数再次返回它。你必须处理回调。这是可行的工作示例,肯定需要调整,因为我们不知道auth函数内部是什么:
mysql= require('mysql');
var connection = mysql.createConnection({});
function check_auth(input, callback){
var sql = "query to mysql";
connection.query(sql, function(err, results) {
if (err) callback(err);
if (results.length > 0) {
callback(null, true);
}else{
callback(null, false);
}
}
io.configure(function () {
io.set('authorization', function(req, callback) {
check_auth(req.query.s, function(err, result) {
if (err) {
//handle that error somehow. we dont not structure of Your func.
return console.log('error:(');
}
if(result === true) {
return callback(null, true);
} else {
return callback('notauth', false);
}
});
});
});