So far I didn't add transactions to my project. Now I'm consider my self to upgrade to that level.
If I need to update master table, details table and the logs table I would do something like this.
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);
}
}
In sequlize documentation transaction is something like this
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 });
So my question is how do I embed transactions to my code with out leaving the async / await fashion.
Anyhelp!
You can write down it in this way.
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
})
I prefer to user CLS mechanism for Transaction passing you also don't have to pass transactions to each query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.