【问题标题】:Sequelize transactions inside forEach issue在 forEach 问题中对事务进行后续处理
【发布时间】:2020-08-05 17:18:09
【问题描述】:

我试图将这两个查询包装在这样的事务中

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)

【问题讨论】:

    标签: node.js transactions sequelize.js


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 嗨@Anatoly 感谢您的回答。我刚刚发现我的代码的实际问题并编辑了问题。也许您也可以根据我更新的问题更新您的答案。
    • 什么是实习生?数组还是类集合对象?
    • 对象数组
    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2011-10-09
    相关资源
    最近更新 更多