Riki Ddelfian
Riki Ddelfian

Reputation: 33

Sequelize transactions inside forEach issue

I've tried to wrap these 2 queries on a transaction like this

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

The first query is executed , but following error appear on second query.

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)

Upvotes: 3

Views: 4992

Answers (1)

Anatoly
Anatoly

Reputation: 22813

Try this:

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

Upvotes: 13

Related Questions