Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Consider using Promise.using syntax for transactions #265

@benjamingr

Description

@benjamingr

From your example, doing this:

var Promise = require('bluebird');

knex.transaction(function(t) {

  knex('books')
    .transacting(t)
    .insert({name: 'Old Books'})
    .then(function(row) {

      return Promise.all(_.map([
        {title: 'Canterbury Tales'},
        {title: 'Moby Dick'},
        {title: 'Hamlet'}
      ], function(info) {

        info.row_id = row.id;

        // Some validation could take place here.
        return knex('book').transacting(t).insert(info);

      }));
    })
    .then(t.commit, t.rollback);

}).then(function() {
  console.log('3 new books saved.');
}, function() {
  console.log('Error saving the books.');
});

var Promise = require('bluebird');

Can become this:

knex.transaction(function(t) {
  return knex('books')
    .transacting(t)
    .insert({name: 'Old Books'})
    .then(function(row) {
       return Promise.all(_.map([
         {title: 'Canterbury Tales'},
         {title: 'Moby Dick'},
         {title: 'Hamlet'}
        ], function(info) {
        info.row_id = row.id;
        // Some validation could take place here.
        return knex('book').transacting(t).insert(info);
      }));
    });
}).then(function() { // this happens if the above promise resolved.
  console.log('3 new books saved.');
}, function() { // this happens if the promise returned from the transaction rejected
  console.log('Error saving the books.');
});

See https://github.com/petkaantonov/bluebird/blob/iterators/API.md#resource-management

Even the transacting(t) part could be removed here, you can also use .bind to set the this value to the transaction.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions