How to avoid nesting when saving associated objects?

坚强是说给别人听的谎言 提交于 2019-12-11 13:36:32

问题


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?


回答1:


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);
    )
 );


来源:https://stackoverflow.com/questions/38008348/how-to-avoid-nesting-when-saving-associated-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!