事务无法回滚,因为它已经完成。

3

我正在尝试创建一个订单并将订单与产品和数量关联:

const t = await sequelize.transaction();
  try {
    const local_orderInstance = await LocalOrder.create({
      user: req.body.client,
      timestamp: Date.now(),
    }, {transaction: t})
    for(let order_item of req.body.items) {
      const order_itemInstance = await LocalOrderItem.create({
        quantity: order_item.quantity,
        ProductReference: order_item.reference,
        LocalOrderId: local_orderInstance.id
      }, {transaction: t})
      await t.commit()
      res.json({message: `successfully saved order`})
    }
  } catch(error) {
    await t.rollback()
    res.status(503).json(error)
  }

enter image description here

如您所见,这与 Sequelize 文档中的示例非常相似,但有一件奇怪的事情正在发生,即使数据库中所有插入操作都没有错误(调用了 t.commit()),它似乎仍然进入 catch 部分并尝试回滚。之后我会收到错误“Transaction cannot be rolled back because it has been finished with state: commit”。 为什么即使没有抛出异常,它仍然尝试执行 catch 部分? 我还收到了“[DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.”的提示。它真的想让我 try catch 回滚吗? 我试过了,但是我得到了“Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client”的错误。 Nodejs 出了问题吗?


1
可能你在一个迭代中调用了commit,但在接下来的某个地方失败了。 - apple apple
4
循环后应进行提交(commit)操作,或者在每次迭代中创建新的事务(transaction)对象。 - apple apple
1
哦,我没意识到我在循环中提交了,真糟糕。 - Imu Sama
1
好的,问题解决了,谢谢。我想我需要休息一下 :D - Imu Sama
很高兴能帮到你 :) - apple apple
1个回答

3
你应该在循环后提交,或者每次迭代都创建一个新的事务对象。
const t = await sequelize.transaction();
  try {
    const local_orderInstance = await LocalOrder.create({
      user: req.body.client,
      timestamp: Date.now(),
    }, {transaction: t})
    for(let order_item of req.body.items) {
      const order_itemInstance = await LocalOrderItem.create({
        quantity: order_item.quantity,
        ProductReference: order_item.reference,
        LocalOrderId: local_orderInstance.id
      }, {transaction: t})  
    }
    await t.commit() // <--- move outside of loop
    res.json({message: `successfully saved order`})
  } catch(error) {
    await t.rollback()
    res.status(503).json(error)
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接