Himmators Himmators - 5 months ago 12
Node.js Question

How to avoid nesting when saving associated objects?

I'm building my first sequelize model, as you can see it results in a lot of nesting when creating the associated objects

var values = [],
userAttributes = sequelize.models.userAttributes,
user = User.build(),
name = userAttributes.build({name: 'name', value: 'params.name'}),
fbprofile = userAttributes.build({name: 'fbprofile', value: 'params.fbprofile'}),
phone = userAttributes.build({name: 'phone', value: 'params.phone'});

user.save().then((user) => {
name.save().then((name) => {
fbprofile.save().then((fbprofile) => {
phone.save().then((phone) => {
user.addUserAttributes([name, fbprofile, phone]);
});
});
});
});


How can I avoid this?

Answer

Sequelize has a Bluebird promise instance. From that you can use the Promise.all method

var values = [],
    userAttributes = sequelize.models.userAttributes,
    user = User.build();

user.save()
  .then((user) => 
    sequelize.Promise.all([
       userAttributes.create({name: 'name', value: 'params.name'}),
       userAttributes.create({name: 'fbprofile', value: 'params.fbprofile'}),
       userAttributes.build({name: 'phone', value: 'params.phone'})
    ])
    .then((recordsArray) => 
       user.addUserAttributes(recordsArray);
    )
 );