[英]Meteor.method hangs on call
I have a meteor code that calls an method on the server. 我有一个流星代码,该流星代码在服务器上调用一个方法。 The server code executes an API call to the USDA and puts the resulting json set into a array list. 服务器代码执行对USDA的API调用,并将生成的json集放入数组列表中。 The problem is that after the Meteor.call on the client side, it hangs. 问题在于客户端上的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.");
}
});
}
After the call to the server and the API returns data to the console and writes it to the array, it doesn't process the console.log on the client side 1 line below the method call. 调用服务器和API之后,将数据返回到控制台并将其写入数组后,它不会处理方法调用下方客户端第1行上的console.log。 How can I fix this? 我怎样才能解决这个问题?
You forgot to give your client side call a callback function. 您忘记给客户端调用回调函数。 Method calls on the client are async, because there are no fibers on the client. 客户端上的方法调用是异步的,因为客户端上没有光纤。 Use this: 用这个:
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;
}
});
}
EDIT: 编辑:
You must also call return
on the server: 您还必须在服务器上调用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.