Bookshelfjs:一个事务中的多个函数

Bookshelfjs : Multiple functions in a transaction

我试图在单个事务中包含多个函数。虽然它没有抛出任何错误,但交易没有得到提交。

下面是示例片段。

function doSomething(ids){
    bookshelf.transaction(function(trx){
        if(someCondition){
            new Service().save({ 'name': service.name },{transacting:trx}).then(function(){
                doSomeDBUpdate1(ids,trx);
            });

        }else{
            doSomeDBUpdate1(ids,trx);
        }
    })
}

function doSomeDBUpdate1(ids,trx){
    new accounts({ id: accountId }).services().attach(serviceIds,{transacting:trx}).then(function(){
    //do something
    })
}

事务不知道您何时完成向它输入新查询...所以现在它永远不会提交。

这应该有效:

function doSomething(ids){
  bookshelf.transaction(function(trx){
    if(someCondition){
      return new Service()
        .save({ 
          'name': service.name 
        }, {transacting:trx})
        .then(function(){
          return doSomeDBUpdate1(ids,trx);
        });
    } else {
      return doSomeDBUpdate1(ids,trx);
    }
  })
}

function doSomeDBUpdate1(ids,trx){
  return new accounts({ id: accountId })
    .services()
    .attach(serviceIds,{transacting:trx})
    .then(function() {
      // do something... if async remember to return the promise
    });
}