我正在使用sequelize事务(托管),当错误引发回滚并不是真的发生时,也许我在这里做错了什么?
我的测试用例:当代码块2抛出错误时,代码块1中完成的事情不会回滚,请帮忙。
return sequelize.transaction(function (t) {
return db.VenueTag.destroy({where: {venueId: venue.venueId}}, {transaction: t}).then(function () {
}, {transaction: t}).then(function () {
//block 1
return db.VenueTag.upsert({
...
});
}, {transaction: t}).then(function () {
//block 2
//update venue details
return venue.updateAttributes({
...
},{ transaction: t});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
return res.status(200).json(result);
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
return res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
});
答案 0 :(得分:2)
你的承诺链中有错误,试试这个:
return sequelize.transaction(function (t) {
return db.VenueTag.destroy({where: {venueId: venue.venueId}}, {transaction: t})
.then(function () {
//block 1
return db.VenueTag.upsert({
...
}, {transaction: t});
.then(function () {
//block 2
//update venue details
return venue.updateAttributes({
...
},{ transaction: t});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
return res.status(200).json(result);
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
return res.status(500).send({
message: errorHandler.getErrorMessage(err)
});
});
答案 1 :(得分:0)
如果您要迎合ES7受众或使用node.js。您可以使用async / await方法来简化回调/承诺链:
/*Global Setup*/
async function deleteVenueTag () {
try {
let transaction = await sequelize.transaction();
let VenueTag = await db.findOne({where: {venueId: venue.venueId}}, {transaction});
await VenueTag.destroy({ transaction });
await VenueTag.upsert({ transaction });
await venue.updateAttributes({ transaction });
await transaction.commit();
}
} catch (error) {
transaction.rollback();
}
答案 2 :(得分:-1)
如果你在使用下面这样的东西
return Users.update(updateUser, {
where: {
uid: sessionUser.uid,
status: 'ACTIVE'
},
transaction: t //second parameter is "options", so transaction must be in it
})
然后 transaction 是第二个选项参数中的一个键,而不是第三个