Maverick
Maverick

Reputation: 454

Bookshelfjs : Multiple functions in a transaction

I am trying to wrap multiple functions in a single transaction. Though it is not throwing any error but the transaction is not getting committed.

Below is the sample snippet.

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
    })
}

Upvotes: 0

Views: 380

Answers (1)

Mikael Lepistö
Mikael Lepistö

Reputation: 19718

Transaction doesn't know when you have finished entering new queries to it... so now it never commits.

This should work:

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
    });
}

Upvotes: 1

Related Questions