我在使用 Meteor.call
时遇到困难回调。我定义了一个从服务器端检索值的函数;但是,它不会将它们返回到模板,以便使用 {{#each}}
循环它们。环形。
这是函数:
search: function() {
Meteor.call('mySearchFunction', arg1, function(err, res) {
if (err) console.log(err);
else if(res) {
console.log(res);
return res;
}
});
}
console.log(res)
显示了我需要的数据,这些数据是通过 mySearchFunction
正确获取的,但我无法将它传递给模板处理程序,尽管它是一个可以迭代的数组。所以我尝试了以下方法:
search: function() {
var s = Meteor.call('mySearchFunction', arg1, function(err, res) {
if (err) console.log(err);
else if(res) {
console.log(res);
return res;
}
});
console.log(s);
return s;
}
和console.log(res)
继续显示必要的数据,但console.log(s)
显示为 undefined
。我认为这是因为 meteor 返回的异步性质s
之前res
有机会在服务器端进行评估。不管怎样,奇怪的是我无法从存储在辅助函数中的辅助函数返回数据。
最佳答案
在客户端,Meteor.call
是异步的 - 它返回 undefined
并且其返回值只能通过回调访问。另一方面,助手同步执行。查看this question的答案了解如何从助手调用方法。这是一个快速解决方案:
$ meteor add simple:reactive-method
Template.showPost.helpers({
search: function () {
arg = Session.get('currentSearch');
return ReactiveMethod.call('mySearchFunction', arg);
}
});
我不确定您的原始帖子中的 arg1
是什么,因此我在解决方案中使用了 session 变量,但这应该会让您走上正确的轨道。
这个包的问题是它可能会鼓励不良行为,但对于不改变状态的方法调用(例如搜索)来说应该没问题。
另请参阅 this post 中有关助手的部分.
关于javascript - Meteor.call() 回调不将值返回到模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29356360/