简体   繁体   English

在 if else 条件下回滚事务 knex

[英]Rollback transaction knex in if else condition

I have this code using transaction in knex我在 knex 中有使用事务的代码

knex.transaction(async trx => {

        try {
            const ids = await knex('team').insert({id: 6, name: "test1"}).transacting(trx);
            const idsNew = await knex('team').insert({id: 7, name: "test2"}).transacting(trx);

            if(condition){
                await trx.rollback();
            }
        } catch (err) {
            console.log(err)
        }
      })

when conditon == true I run rollback transaction and database have not new data.当条件 == 真我运行回滚事务和数据库没有新数据。 But log throw error (node:32723) UnhandledPromiseRejectionWarning: Error: Transaction rejected with non-error: undefined但是日志抛出错误(node:32723) UnhandledPromiseRejectionWarning: Error: Transaction rejected with non-error: undefined

Anyone help me explain this error and help me solve this problem ?有人帮我解释这个错误并帮我解决这个问题吗? Thanks!谢谢!

When transaction handler function returns a promise (async functions always does that), it means that knex implicitly commits / rollsback when that promise resolves / rejects.当事务处理函数返回一个承诺(异步函数总是这样做)时,这意味着当承诺解决/拒绝时knex隐式提交/回滚。

That was the first problem with code above.这是上面代码的第一个问题。 Next problem which from that error message comes is that trx.rollback() needs an argument.来自该错误消息的下一个问题是trx.rollback()需要一个参数。 trx.rollback(new Error("Condition caused rollback!"));

Here is code that should work:这是应该可以工作的代码:

knex.transaction(async trx => { knex.transaction(async trx => {

    try {
        const ids = await knex('team').insert({id: 6, name: "test1"}).transacting(trx);
        const idsNew = await knex('team').insert({id: 7, name: "test2"}).transacting(trx);

        if(condition){
            // this causes handler function to reject the returned promise
            // and knex will do implicit rollback
            throw new Error("Rolling back because of condition");
        }
    } catch (err) {
        console.log(err)
    }
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM