我正在尝试从节点功能查询sqlite3。根据结果,它应该返回TRUE或FALSE回到调用代码。这就是我所做的,但总是得到'未定义':
var sqlite3 = require("sqlite3").verbose();
var dbOpen = function dbOpen() {
sqlite3 = require('sqlite3').verbose();
db = new sqlite3.Database('./internaldb/OPMSE.db');
}
module.exports.dbOpen = dbOpen;
dbOpen();
mKey = 'AIzaSyCrIYuHJ_jiZqmGYoAs7mxiloB3-OBx5WI';
async function db1() {
function db2() {
db.each("SELECT STATUS status FROM API_Keys WHERE KEY = ? AND STATUS = ?", [mKey, '1'], (err, row, x) => {
var keyValid = false;
if (err) {
console.log('There is an error in API Validation')
} else {
console.log(keyValid + '<--This is from upper fun')
keyValid = true;
return keyValid;
}
db.close();
return keyValid;
});
} // db2
d = await db2();
console.log(d + '<--Supposed to return TRUE or FALSE')
} //db1
x = db1();
console.log(x)
/*Returns:
Promise { <pending> }
undefined<--Supposed to return TRUE or FALSE
false<--This is from upper fun
*/
答案 0 :(得分:1)
如果你让db2返回一个promise它会起作用,如果你想知道密钥是否在数据库中,最好select count
它会返回一条记录并且你不会忘记密码。需要db.each
(不确定获取一条记录的方法)。
以下是包含一些注释的代码,这应该可行:
var sqlite3 = require("sqlite3").verbose();
var dbOpen = function dbOpen() {
sqlite3 = require('sqlite3').verbose();
db = new sqlite3.Database('./internaldb/OPMSE.db');
}
module.exports.dbOpen = dbOpen;
dbOpen();
mKey = 'AIzaSyCrIYuHJ_jiZqmGYoAs7mxiloB3-OBx5WI';
async function db1() {
function db2() {
//return a promise
return new Promise(
(resolve,reject)=>
db.serialize(
function() {
var keyValid = false;
db.each(//maybe not use each but just get one record and select count(*)
"SELECT STATUS status FROM API_Keys WHERE KEY = ? AND STATUS = ?",
[mKey, '1'], (err, row, x) => {
if (err) {
reject(err);//reject on error
} else {
console.log(keyValid + '<--This is from upper fun');
keyValid = true;
}
}
);
db.colose();
}
)
)
} // db2
d = await db2();
console.log(d + '<--Supposed to return TRUE or FALSE')
} //db1
x = db1();
console.log(x)