After commit hook

A transaction object allows tracking if and when it is committed.

An afterCommit hook can be added to both managed and unmanaged transaction objects:

  1. sequelize.transaction(t => {
  2. t.afterCommit((transaction) => {
  3. // Your logic
  4. });
  5. });
  6. sequelize.transaction().then(t => {
  7. t.afterCommit((transaction) => {
  8. // Your logic
  9. });
  10. return t.commit();
  11. })

The function passed to afterCommit can optionally return a promise that will resolve before the promise chainthat created the transaction resolves

afterCommit hooks are not raised if a transaction is rolled back

afterCommit hooks do not modify the return value of the transaction, unlike standard hooks

You can use the afterCommit hook in conjunction with model hooks to know when a instance is saved and available outsideof a transaction

  1. model.afterSave((instance, options) => {
  2. if (options.transaction) {
  3. // Save done within a transaction, wait until transaction is committed to
  4. // notify listeners the instance has been saved
  5. options.transaction.afterCommit(() => /* Notify */)
  6. return;
  7. }
  8. // Save done outside a transaction, safe for callers to fetch the updated model
  9. // Notify
  10. })