我有这个承诺链。在第二个承诺中,我需要用户,这是user.save返回的。如何在不破坏承诺链的情况下获得它?我需要它成为一个链,因为我需要最后的承诺将正确的属性返回到调用函数的承诺。
我称之为这样的方法:
User.createRider(req.query).then((user) => {
res.json(user);
});
User = sequelize.define('user', {},{
classMethods: {
createRider: function(params) {
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 = user.save()
.then(sequelize.Promise.all([
fbprofile.save(),
name.save(),
phone.save()
])
)
.then((attributes) => {
user.addUserAttributes(attributes);
return user;
});
return user;
}
}
});
答案 0 :(得分:3)
如果我理解了你所需要的东西,你可以尝试像这样的代码:
user = user.save()
.then(savedUser => {
return sequelize.Promise.all([
fbprofile.save(),
name.save(),
phone.save()
])
.then((attributes) => {
console.log(savedUser); // this guy
user.addUserAttributes(attributes);
return user;
});
});
答案 1 :(得分:1)
我认为这就是你要找的东西:
user = user.save();
let seq = user.then(sequelize.Promise.all([
fbprofile.save(),
name.save(),
phone.save()
]));
return Promise.all([user,seq])
.then((results) => result[0].addUserAttributes(results[1]));
答案 2 :(得分:0)
我不确定,我完全理解你的代码/意图,但我认为你正在寻找某事。像这样:
User = sequelize.define('user', {},{
classMethods: {
createRider: function(params) {
var userAttributes = sequelize.models.userAttributes;
var attrs = [
{name: 'name', value: params.name},
{name: 'fbprofile', value: params.fbprofile},
{name: 'phone', value: params.phone},
];
return sequelize.Promise.all(Array.prototype.concat(
User.build().save(),
attrs.map(o => userAttributes.build(o).save())
)).then(([user, ...attributes]) => {
user.addUserAttributes(attributes);
return user;
})
}
}
});