如何在knex中实现交易?

How to implement transaction in knex?

如果使用了函数,如何在knex中实现交易? util.insert 在 table2 上调用 knex,类似地 util.mark。

 knex('tab1').where({ col1: 'val1' }).update({ col2: 'val2'}).returning('col3').then(function(result1) {
                    if (result1 != 0) {
                        var data2 = {
                            "key": "value"
                        };
                      util.insert(data1, function(err1, data2) {
                            if (err1) {
                                cb(err1);
                                return;
                            }
                            util.mark(data2, function(err2, data3) {
                                if (err2) {
                                    cb(err2);
                                    return;
                                }
                                cb(null, true);
                                return;
                            });
                        });
                    } else {
                        cb(null, false);
                    }
                })
knex.transaction((trx) => {
  return knex('tab1')
  .update({ col2: 'val2' })
  .where({ col1: 'val1' })
  .transacting(trx)
  .then((result) => {
    let promise;
    if (result1 != 0) {
      promise = util.insert(data1);
    } else {
      promise = util.mark(data2);
    }
    return promise
    .transacting(trx);
  })
  .then(trx.commit)
  .catch(trx.rollback)
})
.then(() => {
  // blabla
})
.catch((err) => {
  // handle your error together
});

如果util.insertutil.mark进行io操作,他们最好接受trx作为参数。