使用async / await提交/回滚knex事务 [英] Commit/rollback a knex transaction using async/await

查看:887
本文介绍了使用async / await提交/回滚knex事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ES7 async / await proposal https://github.com/yortus/asyncawait\"rel =nofollow noreferrer>这个模块来模仿它。我试图让 knex.js 交易与他们合作,作为一个起点。

I'm test driving the ES7 async/await proposal using this module to emulate it. I'm trying to make knex.js transactions play well with them, as a starting point.

示例代码:

async function transaction() {
  return new Promise(function(resolve, reject){
    knex.transaction(function(err, result){
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
}

// Start transaction from this call

insert: async (function(db, data) {
 const trx = await(transaction());
 const idUser = await(user.insertData(trx, data));

 return {
    idCidUserstomer: idUser
  }
})

我怎样才能 commit() rollback()如果交易成功或失败?

How can I commit() or rollback() if a transaction succeeds or fails?

推荐答案

建立这个 Knex Transaction with Promises ,它看起来应该是这样的:

Building off of this Knex Transaction with Promises, it looks like it should be along these lines:

// assume `db` is a knex instance

insert: async (function(db, data) {
  const trx = db.transaction();
  try {
    const idUser = await(user.insertData(trx, data));
    trx.commit();
  } catch (error) {
    trx.rollback();
    throw error;
  }

  return {
    idUser: idUser
  }
})

这篇关于使用async / await提交/回滚knex事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆