我是nodejs的新手,并且遇到sqlite select查询的问题
下面是我的代码。
function parse(topic, msg, name) {
item = get_obj(tbl_name, handle, JSON.stringify(arg))
// get item from database
return [handle, arg, item, action];
}
function get_obj(tbl_name, handle, obj_str) {
let dbname = "test.sql";
let query, ret;
let my_obj = {};
let db = new sql.Database(dbname);
let str = "'" + obj_str + "'";
query = "SELECT handle from " + tbl_name + " where object=" + str;
db.serialize(function(ret) {
let ret1 = db.each(query, function(err, row, ret) {
if (err) {
console.log("No records found");
} else {
if (row.handle == handle) {
ret = JSON.parse(obj_str);
}
}
});
});
}
我希望我的解析应该等到我用get_obj()完成。在当前情况下,我的分析立即返回。任何帮助表示赞赏。
最佳答案
如果要在node.js上等待函数完成,则必须使用Promises,请尝试以下代码:
async function parse(topic, msg, name) {
item = await get_obj(tbl_name, handle, JSON.stringify(arg))
// get item from database
return [handle, arg, item, action];
}
function get_obj(tbl_name, handle, obj_str) {
return new Promise(resolve => {
let dbname = "test.sql";
let query;
let db = new sql.Database(dbname);
query = "SELECT handle from " + tbl_name + " where object=?";
db.each(query, [obj_str], function (err, row) {
if (err) {
console.log("No records found");
} else {
if (row.handle == handle) {
resolve(obj_str);
}
}
});
});
}