express - 未经处理的拒绝错误:交易查询已经完成 - knex,express.js
问题描述
我试图首先检查表中的值,如果存在,则删除另一个表中的一行并将此新数据插入该表中。
我使用了一个带有 select、del() 和 insert 命令的事务
db.transaction(trx => {
return trx('users')
.where({ username: user.username })
.select('username')
.returning('username')
.then(retData => {
retUserName = retData[0];
db('profile')
.where({ username: user.username })
.del()
.then(retData => {
return trx
.insert(profileData)
.into('profile')
.returning('*');
});
})
.then(retData => {
res.json({ ProfileData: profileData });
})
.then(trx.commit)
.catch(trx.rollback);
}).catch(err => res.status(400).json('unable to create profile'));
我收到此错误未经处理的拒绝错误:事务查询已完成
但数据尚未添加到表中。
解决方案
您正在从事务处理程序回调中返回承诺,这会导致事务自动提交/回滚,具体取决于返回的承诺是否解析/拒绝。
https://knexjs.org/#Transactions
直接从事务处理函数中抛出错误会自动回滚事务,与返回被拒绝的承诺相同。
请注意,如果在处理程序中未返回承诺,则由您确保调用 trx.commit 或 trx.rollback,否则事务连接将挂起。
在您的代码中,您将这两种不同的方式混合使用事务,这会导致它被提交/回滚两次。
推荐阅读
- javascript - 图表不会在 `onchange` 函数中重绘
- string - 从 String 到 map[string]interface{} golang
- javascript - Protractor Angular 4 E2E意外令牌导入
- c# - 在 Unity 中的最小和最大 X、Y 和 Z 坐标之间移动相机
- javascript - 有没有办法使用 JsDoc 将函数标记为模板文字标记?
- bash - 在 bash 中,有没有办法暂停脚本,让用户输入一些命令,然后在完成后恢复脚本?
- python-3.x - 安装 python-binance 时出错
- php - http.server - 不支持的方法('POST')
- c++ - 可移植的相当于 C++ 中的 getrusage()?
- tableau-api - 时间戳中有间隔的每小时测量:将缺失的记录分配给 0 值