gpt4 book ai didi

javascript - Meteor.method 调用时挂起

转载 作者:行者123 更新时间:2023-12-03 09:43:59 25 4
gpt4 key购买 nike

我有一个 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。我该如何解决这个问题?

最佳答案

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com