gpt4 book ai didi

node.js 使用数组对事务进行 Sequelize 进行查询

转载 作者:行者123 更新时间:2023-12-03 22:24:56 26 4
gpt4 key购买 nike

我想将 clothingModel 上的更新放在事务中,如果它提交,则更新 reservationModel
这是我尝试使用 sequelize.transaction 重写的代码

    try {
data.clothes.forEach(async (clothing) => {
await this.clothingModel.update(
{ price: clothing.price },
{ where: { id: clothing.clothingId } }
);
});
} catch (e) {
//throw exception
}
//if exception is not thrown
this.reservationModel.update(
{ dropoffStatus: 'APPROVED' },
{ where: { id: data.reservationId } }
);
但是我一直在努力使其符合 sequelize 中使用事务的方式
sequelize.transaction(function (t) {
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
});
是否可以?如果是这样,如何?

最佳答案

最好将 transaction 回调转换为 async 使其看起来像顺序代码:

try {
const createdUser = await sequelize.transaction(async t => {
const user = await User.create({
firstName: 'Abraham',
lastName: 'Lincoln'
}, {transaction: t});
await user.setShooter({
firstName: 'John',
lastName: 'Boothe'
}, {transaction: t});
})
});
// transaction committed
.. other code
} catch (err) {
// transaction rolled back
}
循环的附加示例:
await sequelize.transaction(async t => {
for(const clothing of data.clothes) {
await this.clothingModel.update(
{ price: clothing.price },
{ where: { id: clothing.clothingId },
transaction: t
}
);
}
// you can move this `update` outside the callback
// if you wish to execute it out of transaction
this.reservationModel.update(
{ dropoffStatus: 'APPROVED' },
{ where: { id: data.reservationId },
transaction: t
});
});

关于node.js 使用数组对事务进行 Sequelize 进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65030636/

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