错误与资源释放

转账这类多步写库,必须包在事务里保证一致;而比事务更基础的是:从池子借出的连接,无论如何都要还回去。借了不还,连接池很快被占满,新请求全卡死。

错误与资源释放要点

错误与资源释放示例

						async function transfer(fromId, toId, amount) {
						  const conn = await promisePool.getConnection();
						  try {
						    await conn.beginTransaction();
						    await conn.query('UPDATE account SET balance = balance - ? WHERE id = ?', [amount, fromId]);
						    await conn.query('UPDATE account SET balance = balance + ? WHERE id = ?', [amount, toId]);
						    await conn.commit();
						    console.log('转账成功');
						  } catch (e) {
						    await conn.rollback();
						    console.error('转账失败,已回滚:', e.message);
						  } finally {
						    conn.release();
						  }
						}
避坑提醒:把 getConnection 拿到连接写进 try,release 写进 finally,是 Node 连库最稳的模板,记死这个骨架。
错误与资源释放 · Node.js 连接 知识卡片
卡片 08 / 09 · Node.js 连接(1080×1440 速查卡片)

Node.js 连接知识点