本文介绍了保存关联对象时如何避免嵌套?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建我的第一个 sequelize 模型,正如您所看到的,在创建关联对象时会导致大量嵌套

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?

推荐答案

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

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

这篇关于保存关联对象时如何避免嵌套?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 19:07