Meteor.method随叫随到

时间:2015-06-28 01:46:43

标签: javascript meteor

我有一个调用服务器上的方法的流星代码。服务器代码执行对USDA的API调用,并将生成的json集放入数组列表中。问题是在客户端的Meteor.call之后,它会挂起。

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 个答案:

答案 0 :(得分:1)

您忘了给客户端调用回调函数。客户端上的方法调用是异步的,因为客户端上没有光纤。使用此:

$searchterms = mysqli_real_escape_string($database,$_POST['keywords']);
$searchexp = implode("|", str_word_count($searchterms, 1));
$result=mysqli_query($db,"
    SELECT * FROM `products` 
        WHERE `barcode` REGEXP '$searchexp'
        OR `product_name` REGEXP '$searchexp'
        OR `model` REGEXP '$searchexp'
        OR `manufacturer` REGEXP '$searchexp'
");

编辑:

您还必须在服务器上调用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