gpt4 book ai didi

javascript - 如何在异步函数中添加sequelize.js 事务

转载 作者:行者123 更新时间:2023-12-01 01:42:51 26 4
gpt4 key购买 nike

到目前为止,我还没有向我的项目添加交易。现在我正在考虑将自己升级到那个级别。

如果我需要更新主表、详细信息表和日志表,我会这样做。

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);
}
}

在sequulize文档中事务是这样的

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 机制来传递事务,您也不必将事务传递给每个查询。

Automatically pass transactions to all queries

关于javascript - 如何在异步函数中添加sequelize.js 事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52254542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com