首页 > 解决方案 > 未经处理的拒绝错误:交易查询已经完成 - 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'));

我收到此错误未经处理的拒绝错误:事务查询已完成

但数据尚未添加到表中。

标签: expressknex.js

解决方案


您正在从事务处理程序回调中返回承诺,这会导致事务自动提交/回滚,具体取决于返回的承诺是否解析/拒绝。

https://knexjs.org/#Transactions

直接从事务处理函数中抛出错误会自动回滚事务,与返回被拒绝的承诺相同。

请注意,如果在处理程序中未返回承诺,则由您确保调用 trx.commit 或 trx.rollback,否则事务连接将挂起。

在您的代码中,您将这两种不同的方式混合使用事务,这会导致它被提交/回滚两次。


推荐阅读