Skip to content

Instantly share code, notes, and snippets.

@calvintwr
Created April 29, 2015 15:22
Show Gist options
  • Save calvintwr/cff31b4af91abe720ef1 to your computer and use it in GitHub Desktop.
Save calvintwr/cff31b4af91abe720ef1 to your computer and use it in GitHub Desktop.
Transaction with promises, ending with array of promises
return DB.sequelize.transaction(function (t) {
return DB.Something.create({
// data to create
}).then(function(something) {
return [
DB.SomethingElse.create({
aValidatedField: 'aValueThatWould fail validation.'
}),
someInstance.save({fields: ['merchantCredits']})
]
});
}).catch(function(err) {
// error handling
});
/* This will cause a Sequelize validation error to not bubble up to the outer catch, which subsequently doesn't cause a rollback. */
return DB.sequelize.transaction(function (t) {
return DB.Something.create({
// data to create
}).then(function(something) {
return [
DB.SomethingElse.create({
aValidatedField: 'aValueThatWould fail validation.'
}),
someInstance.save({fields: ['merchantCredits']})
]
}).spread(function(somethingElse, someInstance) {
return somethingElse; //just return something thenable makes it work.
});
}).catch(function(err) {
// error handling
});
/* This however, will work. */
@calvintwr
Copy link
Author

If anyone is looking at this gist, the solution is this:

return DB.sequelize.transaction(function (t) {

return DB.Something.create({

    // data to create

}).then(function(something) {

    var promises = [
        DB.SomethingElse.create({
            aValidatedField: 'aValueThatWould fail validation.'
        }),
        someInstance.save({fields: ['merchantCredits']})
    ];
    return Promise.all(promises); 
}).catch(function(err) {
    // error handling
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment