node.js - Node mysql2 异步等待 try catch

标签 node.js promise async-await node-mysql2

我的问题是关于在 Nodejs 中处理异步等待 mysql 查询中的错误。我正在使用 mysql Promise 包装器在 NodeJS 中创建连接池。

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
host: '192.168.0.1',
  user: 'root',
  database: 'h2biz_18_dev',
  waitForConnections: true,
  connectionLimit: 100,
  queueLimit: 0,
  password : 'abc'
})

无法调用 catch block 内的连接释放,因为抛出错误说

Cannot read property 'release' of undefined

如果查询执行抛出错误,是否需要释放catch block 中的连接?如果是这样,在使用 mysql2 的异步等待中释放连接和捕获错误的正确方法是什么?

router.post('/getHolidaysOfYear',async function (req, res, next) {      
    var conn;

try{
    conn = await pool.getConnection();
        // Do something with the connection
    var promise1 = conn.execute(`
    SELECT 
        CALENDAR.*
    FROM
        hrm_calendar_holiday_policy1 CALENDAR
    `);
    const values = await Promise.all([promise1]);
    conn.release();
    return res.status(200).send({success:true, data:values[0][0]});
}

catch(err){
    logger.error(API_NAME + 'error :' + err);
    conn.release();
    return res.status(500).send({success:false, message:'Query Error'});
}
});

最佳答案

看起来甚至在 conn 初始化之前就发生了错误,所以在 pool.getConnection(); 内部。

因此,在您的 catch block 中,变量 conn 为 null,因此它不能/不必被释放。

你可以这样做:

catch(err){
    logger.error(API_NAME + 'error :' + err);
    if(conn !== undefined) //This will check if the conn has already be initialized
        conn.release();
    return res.status(500).send({success:false, message:'Query Error'});
}

关于node.js - Node mysql2 异步等待 try catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52718007/

相关文章:

node.js - Postgresql、Node.js ORM - 相关表中的外键和主键问题(多对多)

node.js - Sequelize : Where is an example of using bulkDelete with criteria?

python - Python 何时会/不会暂停协程的执行?

javascript - 如何测试使用 jest 操作 DOM 的普通 js 代码

node.js - 安装 Node 包类型的最快方法?

javascript - 在多个模块中需要(相同的实例)socket.io

javascript - 函数 promise 在更改为异步后不返回任何内容

javascript - 用 promise 从失败中恢复过来

javascript - 有条件的 promise 链

c# - 为什么等待这个错误任务不抛出异常?