Last active
August 29, 2015 14:21
-
-
Save noherczeg/a05a63fd8f3928590f4d to your computer and use it in GitHub Desktop.
Demystification of functions in sequelizejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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