Check status of sequelize transaction?

Viewed 1785

How to check is transaction executing, commited, or rollbacked?

return sequelize.transaction(function (t) { // return statements }).then(function (res_) { t.commit() }).catch( function (err) { t.rollback(); }); //Here I want to check the transaction status if(t.status != 'committed') { // transaction not committed } }

1 Answers

You're close but you have to structure your code a bit differently. You are using the auto-transactions in Sequelize. When the callback function finishes completely it will commit the transaction automatically for you. Likewise when an error is thrown at any point the transaction will be cancelled automatically. You could check if the transaction is committed by using something like this:

return sequelize
    .transaction(function (t) {
        // Run some queries, do some stuff...
    })
    .then(function () {
        // `t` is not defined, but we know it is committed here
    })
    .catch(function (error) {
        // `t` is not defined, but we know it has been rolled back
    });

If you want to rely on the transaction being committed, you will have to nest your logic for that inside of the then call.

Related