Node.js 7 how to use sequelize transaction with async / await?

前端 未结 6 1192
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 21:43

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

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-29 21:55

    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.

提交回复
热议问题