-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Closed
Labels
Description
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.