在 forEach issue 中对事务进行后续处理
Sequelize transactions inside forEach issue
我试过将这 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`
});
}
我试过将这 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`
});
}