繁体   English   中英

Meteor.method挂起

[英]Meteor.method hangs on call

我有一个流星代码,该流星代码在服务器上调用一个方法。 服务器代码执行对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;
        }
   });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM