Last active
January 16, 2021 02:53
-
-
Save AlfieriChou/9c607cf79fb126b3ed201b21bb10192c to your computer and use it in GitHub Desktop.
sequelize.transaction.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const transaction = async () => { | |
let trx = await sequelize.transaction() | |
try{ | |
const user = await User.create({ | |
first_name: 'wwang', | |
last_name: 'ahahaha' | |
}, {trx}) | |
const updateResult = await User.update({ | |
first_name: 'wang' | |
}, { | |
where: {id: user.dataValues.id} | |
}, {trx}) | |
await trx.commit() | |
} catch (err) { | |
await trx.rollback(new Error('something went wrong')) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// get transaction
const transaction = await sequelize.transaction();
try {
// step 1
await Model.destroy({where: {id}}, {transaction});
// step 2
await Model.create({}, {transaction});
// commit
await transaction.commit();
} catch (err) {
// Rollback transaction if any errors were encountered
await transaction.rollback();
}
https://stackoverflow.com/questions/42870374/node-js-7-how-to-use-sequelize-transaction-with-async-await/43342688#43342688