Lug*_*aru 2 javascript asynchronous node.js sails.js
我需要在我的模型中提供类似关联的东西.所以我有一个带有用户ID的名为Posts的模型,想要从该用户名获取用户名并显示它.
所以我的ForumPosts.js模型如下所示:
module.exports = {
schema: true,
attributes: {
content: {
type: 'text',
required: true
},
forumTopicId: {
type: 'text',
required: true
},
userId: {
type: 'integer',
required: true
},
getUsername: function(){
User.findOne(this.userId, function foundUser(err, user) {
var username = user.username;
});
console.log(username);
return username;
}
}
};
Run Code Online (Sandbox Code Playgroud)
我知道这个返回不起作用,因为它是异步的...但是我如何在我的视图中显示它?在片刻,我用以下方法追溯价值:
<%= forumPost.getUsername() %>
Run Code Online (Sandbox Code Playgroud)
并且肯定得到一个不确定的回报......
所以问题是:我怎样才能返回这个值 - 或者是否有比实例模型更好的解决方案?
提前致谢!
在我的脑海中,您可以在呈现之前异步加载关联的用户:
loadUser: function(done){
var that = this;
User.findOne(this.userId, function foundUser(err, user) {
if ((err)||(!user))
return done(err);
that.user = user;
done(null);
});
}
Run Code Online (Sandbox Code Playgroud)
然后在你的控制器动作中:
module.exports = {
index: function(req, res) {
// Something yours…
forumPost.loadUser(function(err) {
if (err)
return res.send(err, 500);
return res.view({forumPost: forumPost});
});
}
}
Run Code Online (Sandbox Code Playgroud)
在你看来:
<%= forumPost.user.username %>
Run Code Online (Sandbox Code Playgroud)
这是一种快速而肮脏的方式.对于更加可靠和长期的解决方案(到目前为止仍处于开发阶段),您可以使用Associations API查看Sails v0.10.0的alpha版本.
| 归档时间: |
|
| 查看次数: |
2485 次 |
| 最近记录: |