我正在尝试创建一个订单并将订单与产品和数量关联:
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)
}
如您所见,这与 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 出了问题吗?