2013-05-21 30 views
0

我在玩meteorjs,很難找出我寫的異步方法到底發生了什麼。Meteorjs方法調用返回undefined即使有回調

//in methods.js 
feedbackTag = new Meteor.Collection('feedbackTag'); 

Meteor.methods({ 
    searchTag: function (tag, collections) { 
    var result; 
    if(collections.toLowerCase() == 'feedback') 
    { 
    result = feedbackTag.find({tag: tag}); 
    } 
    return result; 
    } 
}); 

//in client.js 
    Template.executefb.events({ 
'keyup input#searchFeedback': 
    function(e) { 
    if(e.which == '13') 
    { 
     var tag = $('#searchFeedback').val(); 
     Meteor.call('searchTag', tag, 'feedback', function(err, data){ 
     //err returns:Internal server error, data returns undefined 
     console.log(err, data) 
     }); 
    } 
    } 
}); 

我真的不知道爲什麼它會返回一個內部服務器錯誤:500。任何建議請。

在此先感謝!

更新:

我意識到,結果變成「未定義」時,它在客戶端被調用。但是,如果我直接從客戶端撥打,即

var result = feedbackTag.find({tag: tag}); 

它向我返回我想要的數據。

任何想法如何從方法類而不是結果?謝謝

+0

您的項目結構如何?如果您沒有使用Meteor.isServer或Meteor.isClient條件,則必須將這些文件放在/ client和/ server文件夾中才能正常工作(methods.js將變爲/server/methods.js,client.js會成爲/client/client.js) –

+0

嗨,很抱歉。這只是代碼的一部分。該代碼分別具有Meteor.isClient和Meteor.isServer。問題是當我創建下面的方法,並用回調調用Meteor.call時,它總是返回錯誤500。 –

回答

3

嘗試將.fetch()添加到服務器上的收集呼叫。這將返回一個實際的數據數組,否則你會返回一個遊標,就像在Meteor.publish()中一樣。

這可能是導致錯誤的原因。

Meteor.methods({ 
     searchTag: function (tag, collections) { 
     if(Match.test(tag, String) && Match.test(collections, String) { 
      if(collections.toLowerCase() === 'feedback') { 
      return feedbackTag.find({tag: tag}).fetch(); 
      } else { 
      console.log("Should have sent feedback, sent " + collections); 
      } 
     } else { 
      throw new Meteor.Error(400, "Invalid inputs!"); 
     } 
    }); 

我修改您的代碼一點,因爲這將是明智的開始拋出自己的錯誤,它也將是明智的使用流星的新的匹配包來驗證您的輸入。

方法將返回或者錯誤對象或響應對象。通常情況下,你在接收端會有一個條件,而不是像console.log一樣顯示。

function(err, res) { 
    if(!!err) { 
    alert(err.reason); /* or console.log(err) */ 
    } else { 
    console.log(res); 
    } 
}