我工作的一個流星的項目,我必須說,這是不容易的沒有更多的回調,尤其是對一兩件事:回調!流星 - 爲「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'不是異步的,你的第一個例子應該沒問題。我假設你在客戶端上這樣做,你想確保你正在尋找的用戶在你的客戶端集合中。在你的瀏覽器控制檯中運行'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