【发布时间】:2020-05-10 16:29:08
【问题描述】:
我在一个文件中声明了我的数据库函数,并希望它们返回一个承诺,以便我可以在其他地方重新使用它们。问题是如何结束连接?我知道我可以在我调用数据库函数的每个地方调用conn.end(),但我不能在数据库函数本身中这样做吗?
来电者...
function scanBoard(qrCode) {
getBoard(qrCode)
.then(b => {
board = b;
});
}
DB 函数(注意,代码不会运行,因为它包含我尝试过的所有内容)
function getBoard(qrcode) {
return db.createConnection(dbConfig)
.then(conn => {
let rows = conn.query("SELECT * FROM boards WHERE id = ?", [qrcode])
.then(() => { conn.end() }); // Can't call it here cus it ends conn before rows is set
conn.end(); // Can't call it here cus rows is still pending
if (rows.length >= 1)
return rows[0];
return null;
})
.finally({
conn.end(); // Can't call it here cus it gets called before the 'then' block in the caller
});
}
【问题讨论】:
-
let rows = conn.query(rows 永远不会在这里设置..cus it ends conn before rows is set不,那是行,只是它会被传递到参数中。 -
IOW:
.then((rows) => { /* rows is here*/ conn.end() });
标签: javascript mysql node.js mariadb