[英]Sequelize transaction Not doing rollback when error throws
I am using sequelize transaction (managed) and when error throws rollback is not really happening, maybe i am doing something wrong here ? 我正在使用sequelize事务(托管),并且当错误抛出回滚没有真正发生时,也许我在这里做错了吗?
my test case : when code block 2 throws an error the things done in code block 1 are not rolled back, please help. 我的测试用例:当代码块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)
});
});
You had mistakes in your promise chain, try this: 您的诺言链中有错误,请尝试以下操作:
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)
});
});
If you're catering to an ES7 audience or using node.js. 如果您要迎合ES7受众或使用node.js。 You can use the async/await approach to simplify the callback/promise chain: 您可以使用async / await方法来简化回调/承诺链:
/*Global Setup*/
let venue, db; // Whatever instances these are....
async function deleteVenueTag () {
let transaction;
try {
transaction = await sequelize.transaction();
let VenueTag = await db.findOne({where: {venueId: venue.venueId}}, {transaction});
if (VenueTag) {
await VenueTag.destroy({ transaction });
await VenueTag.upsert({ transaction });
await venue.updateAttributes({ transaction });
await transaction.commit();
}
} catch (error) {
transaction.rollback();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.