2014-12-01 81 views
6

我工作的一個流星的項目,我必須說,這是不容易的沒有更多的回調,尤其是對一兩件事:回調!流星 - 爲「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: (....) 
+1

我相當肯定'findOne'不是異步的,你的第一個例子應該沒​​問題。我假設你在客戶端上這樣做,你想確保你正在尋找的用戶在你的客戶端集合中。在你的瀏覽器控制檯中運行'Meteor.users.findOne({username:「john」})',這應該是同步出來的問題。 – Shaded 2014-12-01 19:41:21

+0

findOne應該是同步的和被動的。你是說有時它返回undefined,即使查詢應該返回一個值?請注意,我通常只使用findOne和_id,這可能是我體驗不同行爲的部分原因。 – 2014-12-01 19:42:06

+0

@LarryMaccherone是的,就是這樣。它返回undefined,它應該返回別的東西。我注意到console.log中的數據在routes.js中返回4次:2次使用undefined,2次使用期望的對象。但在視圖中,該對象是未定義的。 – Sw0ut 2014-12-01 20:03:34

回答

4

findOne(yourId)是這相當於find({ _id: yourId}, callback)同步方法。區別在於find()允許您定義回調。如果您未將回調傳遞至find(),則此方法將同步。

check wrapAsync:http://docs.meteor.com/#/full/meteor_wrapasync 它允許您使用async操作以sync樣式編碼。

上EventedMind

免費課程:https://www.eventedmind.com/feed/meteor-meteor-wrapasync

+0

嗨,謝謝。我會在工作中明天通過試驗來告訴你最新情況。 – Sw0ut 2014-12-01 20:09:54

+0

現在在Meteor 1.0上,找不到回叫了。請檢查我的編輯。 – Sw0ut 2014-12-02 08:49:27

0

我的經驗迄今是流星MongoDB的包是這些功能通常不提供回調(出於某種原因插入呢......),該函數是原子(因此同步)。

有流星包,如果你想,可以使MongoDB的異步(我沒有帶任何嘗試)。

我想這種同步方法符合Mongodb的簡單維護目標。關於它的思考,利用節點我的眼中釘之一正在與異步回調瀑布/巢,他們是一個痛苦的創建和維護......希望這會使我的代碼更易於閱讀和理解,並改變...

0
var future = new Future(); 

var _h = Hunts.findOne({huntId}); 

if(_h) { 
     future.return(_h) 
    } else { 
     return future.wait(); 
    } 

on server/startup.js您需要: Future = Npm。要求( '纖維/未來');