我是 NodeJs 的新手,所以我坚持它的异步行为,特别是对基于 KnexJS 模块的 MySQL 数据库的查询
以下是带有查询的函数:
var getNotes = function(owner) {
if(owner !== undefined) {
knex.table('tblnotes').where('public',1).orWhere({ownerName : owner}).select('noteId').then(function(result) {
console.log(result);
return result;
});
}
else {
knex.table('tblnotes').where('public',1).select('noteId').then(function(result) {
console.log(result);
return result;
});
}
}
但是当我使用它时
var query = getNotes(user.username);
console.log("authenticated");
console.log(query);
console.log("--------------------------------------");
return res.render('authindex.ejs', {title : "Index", user : user,data : query});
我记录我得到的结果:
authenticated
undefined
--------------------------------------
[ { noteId: 1 } ]
解决方案 1:使用回调
var getNotes = function(owner, callback) {
if(owner !== undefined) {
knex.table('tblnotes').where('public',1).orWhere({ownerName : owner}).select('noteId').then(function(result) {
console.log(result);
callback(result);
});
}
else {
knex.table('tblnotes').where('public',1).select('noteId').then(function(result) {
console.log(result);
callback(result);
});
}
}
并在以下路线中使用它
getNotes(user.username, function(result){
console.log("authenticated");
console.log(result);
console.log("--------------------------------------");
return res.render('authindex.ejs', {title : "Index", user : user,data : result});
});
解决方案 2:使用承诺
var getNotes = function(owner) {
if(owner !== undefined) {
return knex.table('tblnotes').where('public',1).orWhere({ownerName : owner}).select('noteId');
}
else {
return knex.table('tblnotes').where('public',1).select('noteId');
}
}
并在路由中使用它,如下所示:
getNotes(user.username).then(function(result){
console.log("authenticated");
console.log(result);
console.log("--------------------------------------");
return res.render('authindex.ejs', {title : "Index", user : user,data : result});
});