Search code examples
transactionssequelize.js

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


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


Solution

  • 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();
    }