gpt4 book ai didi

javascript - node-mysql2 Final block 和connection.end()不想被调用

转载 作者:行者123 更新时间:2023-11-29 16:33:40 27 4
gpt4 key购买 nike

我正在使用这个 mysql 包:https://github.com/sidorares/node-mysql2

我当前的功能:

const getDataFromTable = async (table) => {
console.info(`Exporting '${table.name}' table.`);
// prepare connection to MySQL
const connection = await mysql.createConnection({
host: mysqlConfig.host,
user: mysqlConfig.user,
password: mysqlConfig.password,
database: mysqlConfig.database
});


try {
// Async query to database
await connection.query(
`SELECT * FROM \`${table.name}\` WHERE \`${table.idFieldName}\` >${lastIndex} ORDER BY ID ASC`,
(err, results) => {
console.debug(`Exported '${results.length}' records.`);


if (Array.isArray(results) && results.length > 0) {
convertArrayToCvs(results, table);
lastIndex = results.pop().id;

if (table.saveIndex) {
fs.writeFile(indexFileName, lastIndex, error => (error ? console.error(error) : null));
}
}
}
);
} finally {
console.log('Connection end');
await connection.end();
}

我的问题是在脚本执行期间跳过finally block (try正常工作)。我尝试用同样的脚本吃午餐,但没有 try catch 最后 block ,但我仍然遇到 connection.end() 问题,它根本不起作用。

此函数在 setInterval() 中调用,因此我必须关闭每个连接,否则连接太多,并且会发生此错误:UnhandledPromiseRejectionWarning:错误:连接过多

最佳答案

我用下面的代码处理问题:

const getDataFromTable = async (table) => {
console.info(`Exporting '${table.name}' table.`);
// Prepare connection to MySQL
const connection = await mysql.createConnection({
host: mysqlConfig.host,
user: mysqlConfig.user,
password: mysqlConfig.password,
database: mysqlConfig.database
});

try {
// Async query to database
const [results] = await connection.query(`SELECT * FROM \`${table.name}\` WHERE \`${table.idFieldName}\` >${lastIndex} ORDER BY ID ASC`);

console.debug(`Exported '${results.length}' records.`);


if (Array.isArray(results) && results.length > 0) {
convertArrayToCvs(results, table);
lastIndex = results.pop().id;

if (table.saveIndex) {
fs.writeFile(indexFileName, lastIndex, error => (error ? console.error(error) : null));
}
}
} finally {
await connection.end();
}

关于javascript - node-mysql2 Final block 和connection.end()不想被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53737673/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com