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

前端 未结 6 1211
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 21:43

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

6条回答
  •  佛祖请我去吃肉
    2021-01-29 22:17

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

提交回复
热议问题