我试图首先检查表中的值,如果它存在,则删除另一个表中的一行并将此新数据插入该表中。
我使用了一个带有 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'));
Run Code Online (Sandbox Code Playgroud)
我收到此错误未处理的拒绝错误:事务查询已完成
但数据尚未添加到表中。
您正在从事务处理程序回调返回承诺,这会导致事务自动提交/回滚,具体取决于返回的承诺是否解决/拒绝。
https://knexjs.org/#Transactions
直接从事务处理函数抛出错误会自动回滚事务,与返回被拒绝的承诺相同。
请注意,如果处理程序中未返回承诺,则需要确保调用 trx.commit 或 trx.rollback,否则事务连接将挂起。
在您的代码中,您混合使用这两种不同的方式来使用事务,这会导致它被提交/回滚两次。
| 归档时间: |
|
| 查看次数: |
5831 次 |
| 最近记录: |