node-mysql2最后,块和connection.end()不想被调用

时间:2018-12-12 07:03:42

标签: javascript mysql node.js

我正在使用以下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();
}

我的问题是在脚本执行过程中跳过了最终块(尝试正常工作)。我尝试了相同的脚本午餐,但没有尝试catch最终阻止,但是 connection.end()仍然存在问题,该问题根本无法解决。

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

1 个答案:

答案 0 :(得分:0)

我用下面的代码解决了这个问题:

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