我想释放 MySQL 池提供的连接。 在“for”循环中,连接被正确释放,但如果我使用 Promise.All 来异步执行它,我有一些未关闭的连接。 问题是,过了一会儿,我收到错误“连接太多”,我不想增加 max_connection 数。
您是否知道是否出于任何原因无法在异步函数中释放 MySQL 连接?
这是我创建池的方式:
dbPool = mysql2.createPool(Object.assign({}, defaultDBConfig, {
database: 'my_db,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
multipleStatements: true,
dateStrings: true
}));
这是我使用的函数:
/**
* @description Allow to do a generic async forEach loop
* @param {*} array
* @param {*} callback
*/
async function asyncForEachPromised(array, callback) {
await Promise.all(array.map(async (items) => {
await callback(items);
}));
/**
* @description ExecuteQuery a query and return an object which contain the result or an error
* @param {*} dbPool Connection pool
* @param {*} query Query to executeQuery
* @param {*} errorMessage Error message to send to the front-end
* @param {*} elements Array of parameter to send in the query
*/
async function executeQuery(dbPool, query, errorMessage, elements) {
const status = {
error: null,
result: null
};
const { error, connection } = await dbPool.getConnection();
if (error) {
console.log(error);
status.error = 'Error when trying to connect to the database.';
} else {
try {
const [rows] = await connection.promise().execute(query, elements);
connection.release();
status.result = rows;
} catch (err) {
console.log(err);
status.error = errorMessage;
}
}
return status;
}
最后,有一个我使用的代码示例,在这种情况下连接不会被释放:
const elements = [{prop1: 'a'},{prop1: 'b'}];
await asyncForEachPromised(elements, async (element) => {
await executeQuery(dbPool, 'my query', 'my error message', [element.prop1]);
});
但是在这种情况下,它们被正确地释放了:
const elements = [{prop1: 'a'},{prop1: 'b'}];
for (const [,element] of elements.entries()) {
await executeQuery(dbPool, 'my query', 'my error message', [element.prop1]);
}
最佳答案
你不能那样做。
试试这个
Promise.all( arr )
.then( results => //your code with results)
.finally( () => //close connection)
.catch( e => //do what you need )
但是...您真的应该尝试使用连接池。你用什么 ? mysql Node ? https://github.com/mysqljs/mysql#pooling-connections
关于javascript - 在 Promise.All 中释放 MySQL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596154/