JS - 如何使用链式承诺结束数据库连接



我在一个文件中声明我的数据库函数,并希望它们返回一个承诺,以便我可以在其他地方重用它们。问题是如何结束连接?我知道我可能会在调用数据库函数的每个地方调用conn.end(),但我不能在数据库函数本身中执行此操作吗?

访客。。。

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

希望这有帮助。

conn.query

是异步的,因此then将在查询产生任何结果之前完成并触发finally,即使只需要几毫秒。不管你是否在解决承诺,封闭的承诺将实现,或者更确切地说,链式then将实现。

async function getBoard(qrcode) {
const conn = await db.createConnection(dbConfig);
try {
return await conn.query("SELECT * FROM boards WHERE id = ?", [qrcode]);
} finally {
conn.end();
}
}

只是一个提示 - 如果此应用程序持续运行,您只需连接到数据库一次并重用连接,则无需为每个查询打开和关闭连接。

我认为这里最好的解决方案是遵循最佳实践...... 为了解决您的问题,我认为最好使用 if 在承诺链的finally部分中处理conn.end();,这样它只有在查询顺利或没有待处理的请求时才会被触发。我会这样做:

.finally({
if(conn){
conn.end();
}
});

显然,您必须从源代码的任何其他部分中删除conn.end();代码行。我什至会考虑用更catch()检查其他错误.

希望它能帮助我解决您想要的任何问题。

async function scanBoard(qrCode)
{
let board = await getBoard(qrCode);
}
catch (e)
{
throw e;
}
}
async function getBoard(qrcode)
{
let dbConn = await  db.createConnection(dbConfig);
let rows = await dbConn.query("SELECT * FROM boards WHERE id = ?", [qrcode]);
if (rows.length >= 1)
// If you need to re-use connection, create a connection instance and re-use.Do not close here
return rows[0];            
}

最新更新