2014-09-26 75 views
5

如何使用Meteor wrapAsync流星包裝異步語法

下面是什麼,我試圖做

if (tempTreatment.groupId === undefined) { 
     // create new group 
     Meteor.wrapAsync(Meteor.call('createTreatmentGroup', salon, tempTreatment.groupName, tempTreatment.groupName)); 

     // get group id 
     var getGroup = Meteor.wrapAsync(Meteor.call('getTreatmentGroup', salon, tempTreatment.groupName)); 

     console.log(getGroup); 
     tempTreatment.groupId = getGroup._id; 
} 

我想synchronosly運行這兩個Meteor.call功能,但我得到undefinedconsole.log(getGroup);其shuold只返回一個對象。

回答

7

Meteor.wrapAsync是一個服務器端API,旨在將Node.js異步函數包裝爲需要回調作爲最後一個參數,以使它們通過使用Future(光纖子庫)顯示爲同步。 (更多信息請見:https://www.discovermeteor.com/blog/wrapping-npm-packages/

它並不打算用於客戶端將異步Meteor.call轉換爲同步調用,因爲在瀏覽器中,Remote Method Invokation調用始終是異步的。長話短說,你根本無法實現你想要做的事情,你必須使用回調函數,並在第一次方法調用的成功回調中嵌套你的第二個方法調用。

+1

在0.9.3中有[Meteor.wrapAsync](http://docs.meteor.com/#meteor_wrapasync),可以在任何地方使用。這是錯誤嗎? – 2014-09-26 11:37:13

+3

我沒有注意到。我認爲他們製作了Meteor.wrapAsync的客戶端版本,以便使用它的代碼可以放入共享文件夾中而不會觸發錯誤,但實際上這是用於服務器的。如果沒有提供回調,'wrapAsync'的客戶端版本只是簡單地定義一個標準的'logErr'回調來代替,它只是記錄錯誤(如果存在):https://github.com/meteor/meteor/blob/ 9608e6205019b69a302cde62e21fcae1c7d22e3d /包/流星/ helpers.js#L108 – saimeunt 2014-09-26 12:12:53