3

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;
            }
        }
    }
});

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;
    }
});

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.

(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.

codingbear
  • 296
  • 5
  • 18

1 Answers1

13

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.

David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • Thanks your solution worked perfectly in resolving the issue. I am also going to read your post on helpers. – codingbear Feb 21 '15 at 02:19