Node.js 7 how to use sequelize transaction with async / await?

qiushijie picture qiushijie · Mar 18, 2017 · Viewed 58.6k times · Source

Node.js 7 and up already support async/await syntax. How should I use async/await with sequelize transactions?

Answer

user7403683 picture user7403683 · Apr 11, 2017
let transaction;    

try {
  // get transaction
  transaction = await sequelize.transaction();

  // step 1
  await Model.destroy({where: {id}, transaction});

  // step 2
  await Model.create({}, {transaction});

  // step 3
  await Model.update({}, {where: {id}, transaction });

  // commit
  await transaction.commit();

} catch (err) {
  // Rollback transaction only if the transaction object is defined
  if (transaction) await transaction.rollback();
}