我在一个文件中声明我的数据库函数,并希望它们返回一个 promise ,以便我可以在其他地方重复使用它们。问题是如何结束连接?我知道我可能可以在调用 DB 函数的每个地方调用 conn.end()
但我不能在 DB 函数本身中执行此操作吗?
来电者...
function scanBoard(qrCode) {
getBoard(qrCode)
.then(b => {
board = b;
});
}
数据库函数(注意,代码不会运行,因为它包含我尝试过的所有内容)
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
});
}
最佳答案
我不建议在每次数据库方法调用后关闭连接。它的效率非常低,您可以使用连接池。请参阅此处了解更多详细信息
https://www.npmjs.com/package/mysql#pooling-connections
当所有工作完成后,您可以关闭池中的连接。看这个
https://www.npmjs.com/package/mysql#closing-all-the-connections-in-a-pool
希望这有帮助。
关于javascript - JS - 如何使用链式 promise 结束数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59894851/