在辅助函数中获取流星方法返回值 [英] Get Meteor Method Return Value Inside Helper Function

查看:65
本文介绍了在辅助函数中获取流星方法返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在服务器/functions.js文件中具有以下内容:

I have the following in server/functions.js file:

Meteor.methods({
    checkIfVoted: function (postId) {
        if (postId) {
            ...
            if (condition is met) {
                return true;
            } else {
                return false;
            }
        }
    }
});

然后在 client /showPost.js中添加以下内容:

And then the following in client/showPost.js:

Template.showPost.helpers({
    alreadyVotedByUser: function () {
        var answer = false;
        if(this) {
            Meteor.call("checkIfVoted", this._id, function(err, response) {
                if (response) { console.log(response); }
                answer = response;
            });
        }
        console.log(answer);
        return answer;
    }
});

当我在console.log中进行响应时,当满足条件时,我得到的值是true,但是answer变量不接受它,并且其值仍然显示为false.

When I am doing the console.log for response I get the value to be true when the condition is met, but the answer variable does not take it, and still shows as having false as its value.

(我知道我将Meteor方法放在服务器目录中,而不是放在要在客户端和服务器之间共享以提供延迟补偿的公共目录中)

(I am aware that I put the Meteor methods in the server directory and not in a common directory to be shared between client and server to provide latency compensation)

请有人帮助我,将不胜感激.

Please if some one could help me with this, it will be highly appreciated.

推荐答案

在客户端上,Meteor.call是异步的-它返回undefined,并且其返回值只能通过回调进行访问.另一方面,帮助程序是同步执行的.请参阅此问题的答案您可以从助手中调用方法.这是一个快速的解决方案:

On the client, Meteor.call is asynchronous - it returns undefined and its return value can only be accesses via a callback. Helpers, on the other hand, execute synchronously. See the answers to this question for how you can call methods from helpers. Here's a quick solution:

$ meteor add simple:reactive-method

Template.showPost.helpers({
  alreadyVotedByUser: function () {
    return ReactiveMethod.call('checkIfVoted', this._id);
  }
});

此程序包的问题在于它可以鼓励不良行为,但是对于不更改状态的方法调用应该没问题.

The problem with this package is that it can encourage bad behavior, but it should be fine for method calls which don't change state.

另请参见这篇文章中有关帮助者的部分.

Also see the section about helpers in this post.

这篇关于在辅助函数中获取流星方法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆