意外拒绝错误:交易查询已完成-knex,express.js
我试图先检查表中的值,如果该值存在,请删除另一个表中的行,并将新数据插入该表中.
I was trying to check for a value in a table first, and if it exists, delete a row in another table and insert this new data into that table.
我使用了带有select,del()和插入命令的事务
I used a transaction with a select, del(), and a insert command
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'));
我收到此错误拒绝拒绝错误:交易查询已完成
I get this error Unhanded rejection error:Transaction query already completed
但数据尚未添加到表中.
but the data hasn't been added to the table.
您正在从事务处理程序回调中返回承诺,这将导致事务自动落实/回退,具体取决于返回的承诺是否解决/拒绝.
You are returning promise from transaction handler callback, which causes transaction to automatically committed / rolled back depending if returned promise resolves / rejects.
https://knexjs.org/#Transactions
直接从事务处理程序函数引发错误 自动回滚交易,就像返回被拒绝的交易一样 答应.
Throwing an error directly from the transaction handler function automatically rolls back the transaction, same as returning a rejected promise.
请注意,如果处理程序中未返回承诺,则承诺已完成 给您以确保调用trx.commit或trx.rollback,否则 事务连接将挂起.
Notice that if a promise is not returned within the handler, it is up to you to ensure trx.commit, or trx.rollback are called, otherwise the transaction connection will hang.
在您的代码中,您混用了这两种使用事务的方式,这导致它被提交/回滚两次.
In your code you are mixing those two different ways to use transactions, which causes it to be committed / rolledback twice.