如何在异步函数中添加sequlize.js事务

时间:2018-09-10 09:15:58

标签: javascript sequelize.js

到目前为止,我还没有向我的项目添加事务。现在,我考虑将自己升级到该级别。

如果我需要更新主表,详细信息表和日志表,我将执行以下操作。

export async function create(req,res,next){
    try{

    const add_to_master_table = await db.Inovice_master.create();

    const add_to_detail_table = await db.Invoice_detail.create();

    const add_to_user_logs = await db.User_logs.create();

    res.sendStatus(200);

    }catch(error){
        res.sendStatus(500);
    }
}

在序列化文档事务中是这样的

return sequelize.transaction(function (t) {

  // chain all your queries here. make sure you return them.
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(function (user) {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });

}).then(function (result) {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});

所以我的问题是如何在不离开异步/等待方式的情况下将事务嵌入代码中。

任何帮助!

1 个答案:

答案 0 :(得分:2)

您可以用这种方式写下来。

// a simple interface
interface Plant {
    public void grow();
}

// apply interface to class
class Eucalyptus implements Plant {
    @Override
    public void grow() {
        System.out.println("This is from Eucalyptus");
    }
}

public class Main {
    public static void main(String[] args) {

        // Create an instance of Eucalyptus
        Eucalyptus eucalyptus = new Eucalyptus();
        eucalyptus.grow();

        // Anonymous class Myrtle from Plant interface
        Plant myrtle = new Plant() {
            @Override
            public void grow() {
                System.out.println("This was running from anonymous class from Plant Interface");
            }
        };

        myrtle.grow();

        // Try to create a lambda expression from Plant interface
        // and override grow() method
        // by print ("This was running from Lambda expression")

        // this won't work. why?
        Eucalyptus eucalyptus1 = new Eucalyptus();
        eucalyptus1.grow(() -> System.out.println("This from Lambda expression"));
    }
}

我更喜欢使用用户CLS机制进行交易传递,您也不必将交易传递给每个查询。

Automatically pass transactions to all queries