【问题标题】:Get Meteor Method Return Value Inside Helper Function在 Helper 函数中获取 Meteor 方法返回值
【发布时间】:2015-04-22 19:20:48
【问题描述】:

我在 server/functions.js 文件中有以下内容:

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

然后在 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 作为其值。

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

如果有人可以帮助我解决这个问题,我们将不胜感激。

【问题讨论】:

    标签: meteor


    【解决方案1】:

    在客户端,Meteor.call 是异步的——它返回undefined,它的返回值只能通过回调来访问。另一方面,助手同步执行。请参阅this question 的答案,了解如何从助手调用方法。这是一个快速的解决方案:

    $ meteor add simple:reactive-method
    
    Template.showPost.helpers({
      alreadyVotedByUser: function () {
        return ReactiveMethod.call('checkIfVoted', this._id);
      }
    });
    

    这个包的问题是它会鼓励不良行为,但对于不改变状态的方法调用应该没问题。

    另请参阅this post 中有关助手的部分。

    【讨论】:

    • 感谢您的解决方案完美地解决了这个问题。我还将阅读您关于助手的帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2019-01-20
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多