Mysql 如何在Nodejs中返回嵌套函数值
我陷入了从函数返回的结果来验证用户的过程中Mysql 如何在Nodejs中返回嵌套函数值,mysql,node.js,Mysql,Node.js,我陷入了从函数返回的结果来验证用户的过程中 utility.isAspAuth = function(token){ queryString = { sql: 'SELECT * FROM SecurityToken WHERE Token = ?', timeout: 40000, // 40s values: [token] }; var curTime = new Date(); connection.quer
utility.isAspAuth = function(token){
queryString = {
sql: 'SELECT * FROM SecurityToken WHERE Token = ?',
timeout: 40000, // 40s
values: [token]
};
var curTime = new Date();
connection.query(queryString,function(err,rows,field){
if(err){
console.log('error on query' + err);
}else{
var result = rows[0];
result.forEach(function(element, index, array){
if(Date.parse(result.Expires) > curTime){
return true;
}else{
return false;
}
});
}
});
};
所以我在另一个文件中调用这个函数,但是结果没有定义
console.log(utility.isAspAuth(token))
有人能给我一些关于如何修理它的提示吗
非常感谢问题是: 当您从另一个文件调用
utility.isaspath(token)
时,utility
文件中的函数正在执行,但在调用时不会返回任何内容
这就是nodejs的本质。请注意,在您的代码中:
查询(查询字符串,函数(错误,行,字段){
只有在查询完成后,才会执行上面一行中的回调函数,这不会连续发生。默认情况下是自动的。这就是为什么您在控制台.log()中得到nothing
即undefined
修复是:
使用承诺-
如果函数不能返回值或抛出异常而不阻塞,则可以返回承诺。”
在实用程序文件中-
utility.isAspAuth = function(token){
var deferred = Q.defer();
/* require('q') in your nodejs code.
You see at the last line of this function we return a promise object.
And in your success / fail function we either resolve/ reject the promise.
Simple. See the usage in other file where you log.
*/
queryString = {
sql: 'SELECT * FROM SecurityToken WHERE Token = ?',
timeout: 40000, // 40s
values: [token]
};
var curTime = new Date();
connection.query(queryString,function(err,rows,field){
if(err){
// console.log('error on query' + err);
deferred.reject(new Error(err));
} else {
var result = rows[0];
result.forEach(function(element, index, array){
if(Date.parse(result.Expires) > curTime){
deferred.resolve(true);
}else{
deferred.resolve(false);
}
});
}
});
return deferred.promise;
};
在你的另一份文件中-
utility.isAspAuth(token)
.then(function (yourBoolResponse) {
console.log(yourBoolResponse);
})
.catch(function (err) {
// Handle error thrown here..
})
.done();
Async,Async,Async。您的连接.query()
函数是异步的。这意味着它在isasauth()
返回很久之后调用它的回调。您不能从这样的函数返回异步值。相反,您必须将回调传递到isasauth()
并在获得最终值时调用该回调,您只能使用该回调中的值。此类问题有数百个重复项。我将寻找一个重复项来标记此问题。请不要发布有许多重复项的问题的答案。相反,只需投票作为重复项关闭。这只是投票如果有很多重复的人都在问同一个问题,那就去看看StackOverflow世界。@jfriend00-是的,我会从现在开始记住这一点。谢谢你的指点。