2015-06-28 41 views
0

我有一個流星代碼,調用服務器上的方法。服務器代碼執行對USDA的API調用,並將生成的json集放入數組列表中。問題是,在客戶端的Meteor.call之後,它掛起。Meteor.method掛斷電話

var ndbItems = []; 

if (Meteor.isClient) { 
    Template.body.events({ 
     "submit .searchNDB" : function(event) { 
      ndbItems = [];  
      var ndbsearch = event.target.text.value; 
      Meteor.call('getNDB', ndbsearch); 
      console.log("This doesn't show in console."); 
      return false; 
     } 
    }); 
} 

if (Meteor.isServer) { 
    Meteor.methods({ 
     'getNDB' : function(searchNDB) { 
      this.unblock(); 
      var ndbresult = HTTP.call("GET", "http://api.nal.usda.gov/ndb/search/", 
       {params: {api_key: "KEY", format: "json", q: searchNDB}}); 
      var ndbJSON = JSON.parse(ndbresult.content); 
      var ndbItem = ndbJSON.list.item; 
      for (var i in ndbItem) { 
       var tempObj = {}; 
       tempObj['ndbno'] = ndbItem[i].ndbno; 
       tempObj['name'] = ndbItem[i].name; 
       tempObj['group'] = ndbItem[i].group; 
       ndbItems.push(tempObj); 
      } 
      console.log(ndbItems); //This shows in console. 
      console.log("This also shows in console."); 
     } 
    }); 
} 

調用服務器和API返回數據到控制檯,並將其寫入到陣列之後,它不處理在方法調用下面的客戶端1行的console.log。我怎樣才能解決這個問題?

回答

1

你忘了給你的客戶端調用回調函數。客戶端上的方法調用是異步的,因爲客戶端上沒有光纖。使用此:

if (Meteor.isClient) { 
    Template.body.events({ 
     "submit .searchNDB" : function(event) { 
      ndbItems = [];  
      var ndbsearch = event.target.text.value; 
      Meteor.call('getNDB', ndbsearch, function(err, result) { 
       console.log("This will show in console once the call comes back."); 
      }); 
      return false; 
     } 
    }); 
} 

編輯:

您還必須調用服務器上的return

if (Meteor.isServer) { 
    Meteor.methods({ 
     'getNDB' : function(searchNDB) { 
      this.unblock(); 
      var ndbresult = HTTP.call("GET", "http://api.nal.usda.gov/ndb/search/", 
       {params: {api_key: "KEY", format: "json", q: searchNDB}}); 
      .... 
      console.log("This also shows in console."); 
      return; 
     } 
    }); 
} 
+0

是內部功能的文本(錯了,結果){}同時等待將要執行的東西對於服務器還是服務器執行完成後執行的東西? –

+0

我錯過了代碼中的另一個問題:您需要在服務器上調用返回。到你的問題:回調時,回調運行。 –