流星 - 为“findOne”功能
我工作的一个流星的项目,我必须说,这是不容易的没有更多的回调,尤其是对一两件事:回调!流星 - 为“findOne”功能
一切都是异步的,所以我想知道我必须怎么做才能从我的mongodb中获得结果。
var user = Meteor.users.findOne({username: "john"});
return (user); // sometimes returns "undefined"
...
var user = Meteor.users.findOne({username: "john"});
if (user) // so ok, I check if it exists!
return (user); // Cool, I got my user!
return(); // Ok and what should I return here? I want my user!
我不想脏了,把喜欢的setTimeout无处不在。 有人有这个解决方案吗?
编辑: 我router.js发现与我的数据返回4倍的console.log。 2次使用未定义的值,另外2次使用期望值。在视图中,它仍然是未定义的。 为什么路由器在这条路由中经过了4次?它是否显示路由器中返回值的第一个结果?
如果find()找不到任何东西,我应该返回什么?
编辑2:下面是一些代码来理解。
this.route('profilePage', {
path: 'profil/:_id?',
waitOn: function() {
return [
Meteor.subscribe('article', { prop: this.params._id}), // id can be id or username
Meteor.subscribe('article', { userId: this.params._id}), // id can be id or username
Meteor.subscribe('params'),
Meteor.subscribe('profil', (this.params._id ? this.params._id : Meteor.userId()))
];
},
data: function() {
if (this.params._id) {
var user = Meteor.users.findOne(this.params._id);
if (!user)
user = Meteor.users.findOne({username: this.params._id});
console.log(user);
return user;
}
else if (Meteor.userId())
return Meteor.user();
else
Router.go("userCreate");
}
});
我得到这个在控制台上: http://puu.sh/debdJ/69419911f7.png
(以下文字版)
undefined
undefined
Object_id: "o3mgLcechYTtHPELh"addresses: (....)
Object_id: "o3mgLcechYTtHPELh"addresses: (....)
findOne(yourId)
是这相当于find({ _id: yourId}, callback)
同步方法。区别在于find()
允许您定义回调。如果您未将回调传递至find()
,则此方法将同步。
check wrapAsync:http://docs.meteor.com/#/full/meteor_wrapasync 它允许您使用async
操作以sync
样式编码。
免费课程:https://www.eventedmind.com/feed/meteor-meteor-wrapasync
我的经验迄今是流星MongoDB的包是这些功能通常不提供回调(出于某种原因插入呢......),该函数是原子(因此同步)。
有流星包,如果你想,可以使MongoDB的异步(我没有带任何尝试)。
我想这种同步方法符合Mongodb的简单维护目标。关于它的思考,利用节点我的眼中钉之一正在与异步回调瀑布/巢,他们是一个痛苦的创建和维护......希望这会使我的代码更易于阅读和理解,并改变...
var future = new Future();
var _h = Hunts.findOne({huntId});
if(_h) {
future.return(_h)
} else {
return future.wait();
}
on server/startup.js您需要: Future = Npm。要求( '纤维/未来');
我相当肯定'findOne'不是异步的,你的第一个例子应该没问题。我假设你在客户端上这样做,你想确保你正在寻找的用户在你的客户端集合中。在你的浏览器控制台中运行'Meteor.users.findOne({username:“john”})',这应该是同步出来的问题。 – Shaded 2014-12-01 19:41:21
findOne应该是同步的和被动的。你是说有时它返回undefined,即使查询应该返回一个值?请注意,我通常只使用findOne和_id,这可能是我体验不同行为的部分原因。 – 2014-12-01 19:42:06
@LarryMaccherone是的,就是这样。它返回undefined,它应该返回别的东西。我注意到console.log中的数据在routes.js中返回4次:2次使用undefined,2次使用期望的对象。但在视图中,该对象是未定义的。 – Sw0ut 2014-12-01 20:03:34