保存关联对象时如何避免嵌套?

时间:2016-06-24 07:53:14

标签: node.js sequelize.js

我正在构建我的第一个续集模型,因为您可以看到它在创建关联对象时会导致大量嵌套

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

我该如何避免这种情况?

1 个答案:

答案 0 :(得分:0)

Sequelize有一个Bluebird承诺实例。从那里你可以使用Promise.all方法

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