73

Node.js 7 and up already support async/await syntax. How should I use async/await with sequelize transactions?

7 Answers 7

172
let transaction;    

try {
  // get transaction
  transaction = await sequelize.transaction();

  // step 1
  await Model.destroy({ where: {id}, transaction });

  // step 2
  await Model.create({}, { transaction });

  // step 3
  await Model.update({}, { where: { id }, transaction });

  // commit
  await transaction.commit();

} catch (err) {
  // Rollback transaction only if the transaction object is defined
  if (transaction) await transaction.rollback();
}
7
  • This doesn't work. t in this case is a Promise and not the transaction object.
    – Pier
    Jun 2, 2017 at 20:24
  • 10
    @Pier, await waits the sequelize.transaction() and then get the result of it. the t is not the promise, it is the result of promise.
    – Hao Wu
    Jun 14, 2017 at 9:31
  • 6
    What if transaction = await sequelize.transaction(); fails? Then transaction.rollback() will throw an error. Do we need to check whether .rollback is available on transaction in catch block?
    – Kunal
    Aug 20, 2018 at 14:09
  • 1
    @Kunal, there should be an "if (transaction)..." clause. I submitted a change request to the code example for peer review.
    – Christoph
    Feb 25, 2019 at 17:14
  • 2
    it is not working in my case untill i pass transaction as key:value. eg in above solution, {transaction:transaction} is working. I am using sequelize version 5.19.2
    – Semicolon
    Nov 26, 2019 at 12:15
65

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.

5
  • Thank you very much, I have been looking for this solution for a while. Didn't realize you could await sequelize.transaction. Oct 6, 2019 at 22:57
  • @hellowill89 - you can check the documentation of a given function. If it returns a Promise, then you can use await.
    – kosinix
    May 22, 2020 at 2:04
  • 1
    Property 'transaction' does not exist on type 'typeof import("/Users/mac/Projects/myinvoice-be/node_modules/sequelize/types/index")'. Did you mean 'Transaction'?ts(2551) I have imported sequelize from import sequelize from 'sequelize'; Feb 16, 2021 at 8:56
  • A nice answer for completeness i suppose but I don't know why I would want the indirection of throwing an error to rollback rather than explicitly just stating it. Maybe if you do it enough times its better but I prefer the explicit version myself.
    – Joel M
    Apr 18, 2021 at 21:20
  • @JoelM its because thats the only way to rollback in a managed transaction. There is no transaction.rollback.
    – kosinix
    Sep 19, 2021 at 1:09
10

If CLS is enabled, Sequelize can use that to keep your transaction object and automatically pass it to all queries inside the continuation-passing cycle.

Setup:

import { Sequelize } from "sequelize";
import { createNamespace } from "cls-hooked"; // npm i cls-hooked

const cls = createNamespace("transaction-namespace"); // any string
Sequelize.useCLS(cls);

const sequelize = new Sequelize(...);

Usage:

const removeUser = async (id) => {
    await sequelize.transaction(async () => { // no need `async (tx)`
        await removeUserClasses(id);
        await User.destroy({ where: { id } }); // will auto receive `tx`
    });
}

const removeUserClasses = async (userId) => {
    await UserClass.destroy({ where: { userId } }); // also receive the same transaction object as this function was called inside `sequelize.transaction()`
    await somethingElse(); // all queries inside this function also receive `tx`
}

How it works?

From Sequelize source code: github.com/sequelize

Check and save transaction to CLS

if (useCLS && this.sequelize.constructor._cls) {
    this.sequelize.constructor._cls.set('transaction', this);
}

Retrieve transaction from CLS and set to options

if (options.transaction === undefined && Sequelize._cls) {
    options.transaction = Sequelize._cls.get('transaction');
}

Read more:

  1. Sequelize: automatically pass transactions to all queries
  2. CLS hooked
  3. Async Hooks
1
  • 1
    Thank you so much for posting an example using CLS. Clean. Aug 29 at 2:12
7

The answer given by user7403683 describes async/await way for unmanaged transaction (http://docs.sequelizejs.com/manual/tutorial/transactions.html#unmanaged-transaction-then-callback-)

Managed transaction in async/await style may look as follows:

await sequelize.transaction( async t=>{
  const user = User.create( { name: "Alex", pwd: "2dwe3dcd" }, { transaction: t} )
  const group = Group.findOne( { name: "Admins", transaction: t} )
  // etc.
})

If error occurs, the transaction is automatically rolled back.

1
3

The above code has an error in destroy call.

 await Model.destroy({where: {id}, transaction});

Transaction is part of the options object.

0
0
async () => {
  let t;

  try {
    t = await sequelize.transaction({ autocommit: true});

    let _user = await User.create({}, {t});

    let _userInfo = await UserInfo.create({}, {t});

    t.afterCommit((t) => {
      _user.setUserInfo(_userInfo);
      // other logic
    });
  } catch (err) {
    throw err;
  }
}
0
0

//try with this

const transaction = await sequelize.transaction({ autocommit: false });
    try {
      await Model.create(data, {transaction})
    } catch (e) {
      if (transaction) await transaction.rollback();
      next(e);
      response.status(500).json({ error: e });
    }

    if (transaction) {
      await transaction.commit();
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.