到目前为止,我还没有在我的项目中添加事务。现在我认为我自己升级到那个级别。
如果我需要更新主表、详细信息表和日志表,我会做这样的事情。
export async function create(req,res,next){
try{
const add_to_master_table = await db.Inovice_master.create();
const add_to_detail_table = await db.Invoice_detail.create();
const add_to_user_logs = await db.User_logs.create();
res.sendStatus(200);
}catch(error){
res.sendStatus(500);
}
}
在 sequelize 文档交易中是这样的
return sequelize.transaction(function (t) {
// chain all your queries here. make sure you return them.
return User.create({
firstName: 'Abraham',
lastName: 'Lincoln'
}, {transaction: t}).then(function (user) {
return user.setShooter({
firstName: 'John',
lastName: 'Boothe'
}, {transaction: t});
});
}).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 callback
});
所以我的问题是如何在不离开异步/等待方式的情况下将事务嵌入到我的代码中。
任何帮助!
你可以用这种方式写下来。
return sequelize.transaction(async (t) => {
let user = await User.create({firstName: 'Abraham', lastName: 'Lincoln'}, { transaction: t })
user = await user.setShooter({ firstName: 'John', lastName: 'Boothe'}, { transaction: t });
return user
})
我更喜欢使用 CLS 机制来传递事务,您也不必将事务传递给每个查询。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句