我有一个流星代码,该流星代码在服务器上调用一个方法。服务器代码执行对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。我怎样才能解决这个问题?

最佳答案

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

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;
        }
   });
}

关于javascript - Meteor.method挂起,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31095352/

10-16 22:00