试图找出在expressjs中使用Sequelize事务的正确方法。 以下代码通过ID查找帖子,从而增加帖子表中的回复计数,更新帖子,然后在回复表中创建回复。试图在控制器操作中调用代码,但它不起作用。内部承诺没有兑现。关于在Sequelize中使用交易的正确方法有何建议?
Sequelize.transaction(function (t) {
db.Post.find({where:{id: postId}}, {transaction:t}).then(function(post)
{
var count = post.reply + 1;
post.update({replyCount:count},{transaction:t});
db.Reply.create(replyData, {transaction:t}).then(function(newcomment, created){
res.json(newcomment);
});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction
});
});
答案 0 :(得分:2)
Sequelize.transaction(function (t) {
return db.Post.find({where:{id: postId}}, {transaction:t}).then(function(post)
{
var count = post.reply + 1;
return post.update({replyCount:count},{transaction:t})
.success(result =>
// i guess you want to use result in here to create replyData
return db.Reply.create(replyData, {transaction:t})
.then(function(newcomment, created){
return res.json(newcomment);
});
);
});
答案 1 :(得分:0)
在事务中的初始.find()没有任何价值。在回滚的情况下,没有什么可以撤消的。仅写入或更新需要在事务中回滚。 try / catch将处理任何失败的查询,并且将自动为事务项触发回滚。
考虑这个更现代的ES6解决方案:
try {
const result = await sequelize.transaction(async (t) => {
// no need to include this in the transaction, it only reads (find)
const post = await db.Post.find({where:{id: postId}});
const count = post.reply + 1;
const updateResult = await post.update({
replyCount: count
}, { transaction: t });
// i guess you want to use result in here to create replyData
const createResult = await db.Reply.create({
replyData,
}, { transaction:t });
return res.json(newcomment);
});
} catch (error) {
// If the execution reaches this line, an error occurred.
// The transaction has already been rolled back automatically by Sequelize!
}
参考: -https://sequelize.org/master/manual/transactions.html#managed-transactions