Skip to content

Instantly share code, notes, and snippets.

@noherczeg
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save noherczeg/a05a63fd8f3928590f4d to your computer and use it in GitHub Desktop.

Select an option

Save noherczeg/a05a63fd8f3928590f4d to your computer and use it in GitHub Desktop.
Demystification of functions in sequelizejs
/**
* Old version
*/
return sequelize.transaction(function (t) {
return User.create({
firstName: 'Abraham',
lastName: 'Lincoln'
}, {transaction: t}).then(function (user) {
return user.setShooter({
firstName: 'John',
lastName: 'Boothe'
}, {transaction: t});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
});
/**
* New version
*/
var newUser = {
firstName: 'Abraham',
lastName: 'Lincoln'
};
var shooter = {
firstName: 'John',
lastName: 'Boothe'
};
return sequelize.transaction(createUser(t))
.then(complete(result))
.catch(rollBack(err));
function createUser (t) {
return User.create(newUser, {transaction: t})
.then(setShooterForUser(user));
}
function setShooterForUser (user) {
return user.setShooter(shooter, {transaction: t});
}
function rollBack (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
}
function complete (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment