The accepted answer is an “unmanaged transaction” that requires an explicit call to commit and rollback . For those who want a “managed transaction”, it looks like this:
try { // Result is whatever you returned inside the transaction let result = await sequelize.transaction( async (t) => { // step 1 await Model.destroy({where: {id: id}, transaction: t}); // step 2 return await Model.create({}, {transaction: t}); }); // In this case, an instance of Model console.log(result); } catch (err) { // Rollback transaction if any errors were encountered console.log(err); }
To rollback, just generate an error inside the transaction function:
try { // Result is whatever you returned inside the transaction let result = await sequelize.transaction( async (t) => { // step 1 await Model.destroy({where: {id:id}, transaction: t}); // Cause rollback if( false ){ throw new Error('Rollback initiated'); } // step 2 return await Model.create({}, {transaction: t}); }); // In this case, an instance of Model console.log(result); } catch (err) { // Rollback transaction if any errors were encountered console.log(err); }
If any code throws an error inside the transaction block, the rollback automatically fires.
kosinix
source share