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

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

问题描述

我在 server/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.

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

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