node-mysql2最终阻止并连接end()不想被调用

jrcvhitl  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(319)

我正在使用这个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块被跳过(请尝试正常工作)。我尝试在没有try-catch-finally块的情况下使用相同的脚本,但是connection.end()仍然存在问题,它根本不起作用。
此函数正在setinterval()中调用,因此我必须关闭每个连接,否则将导致连接过多,并且会出现以下错误:UnhandledPromisejectionWarning:错误:连接过多

wnrlj8wa

wnrlj8wa1#

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

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();
}

相关问题