Node.js 7 and up already support async/await syntax. How should I use async/await with sequelize transactions?
The accepted answer is an "unmanaged transaction", which requires you to call commit
and rollback
explicitly. For anyone who wants a "managed transaction", this is what it would look like:
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 throw 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 that throws an error inside the transaction block, the rollback is automatically triggered.