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

前端 未结 6 1206
没有蜡笔的小新
没有蜡笔的小新 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 22:01

    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.

提交回复
热议问题