gpt4 book ai didi

node.js - 在 forEach 问题中对交易进行 Sequelize

转载 作者:行者123 更新时间:2023-12-03 22:17:52 28 4
gpt4 key购买 nike

我试图将这 2 个查询包装在这样的交易中

const transaction = await db.sequelize.transaction()
try {
await Table1.create({
name: data.name
}, {transaction});

trainees.foreach(async trainee => {
await Table2.create({
name: trainee.name
}, {transaction});
})

await transaction.commit();
api.publish(source, target, false, {message: `Data successfully saved`});
} catch (error) {
await transaction.rollback();
api.error(source, target, {
message: error.message || `Unable to save data`
});
}

执行第一个查询,但在第二个查询中出现以下错误。
commit has been called on this transaction(2f8905df-94b9-455b-a565-803e327e98e1), you can no longer use it. (The rejected query is attached as the 'sql' property of this error)

最佳答案

试试这个:

try {
await db.sequelize.transaction(async transaction => {
await Table1.create({
name: data.name
}, {transaction});

// you should await each iteration
// forEach function of an Array object can't do it
for (const trainee of trainees) {
await Table2.create({
name: trainee.name
}, {transaction});
}
await Table3.create({
name: data.name
}, {transaction});

api.publish(source, target, false, {message: `Data successfully saved`});
})
} catch (error) {
api.error(source, target, {
message: error.message || `Unable to save data`
});
}

关于node.js - 在 forEach 问题中对交易进行 Sequelize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61369310/

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