Boris Daka
Boris Daka

Reputation: 603

How come this isn't working Sync/Async issues with Meteor.methods

This is weird but when I call a external function from Meteor.method function it will always return undefined in the client I tried Meteor.wrapAsync but I think I'm doing something wrong. Here is my code:

var demoFunction = function () {
  //database operations
    var user = this.userId;
    if (!user)
      return;

    var count = Users.aggregate([
      { $group: {_id: null, count: {$sum: 1}} }
    ]);

    if (count[0] && count[0].count)
      return count[0].count;
    return 0;
}

Meteor.methods({
 // NOT WORKING, How can I make this work?
 methodDemo: function () {
   var result = demoFunction ();
   return result;
 },
 // Works
 methodDemo2: function () {
  //database operations
    var user = this.userId;
    if (!user)
      return;

    var count = Users.aggregate([
      { $group: {_id: null, count: {$sum: 1}} }
    ]);

    if (count[0] && count[0].count)
      return count[0].count;
    return 0;
 }
});
// Call from client
Meteor.call("methodDemo", function (err, res) { });

calling external functions doesn't work the same way if I put the code inside the meteor method why?

Upvotes: 0

Views: 34

Answers (2)

Greg Neiheisel
Greg Neiheisel

Reputation: 590

Try using Meteor.userId() in your function instead of this.userId. I think you are loosing the value of this when calling your function causing it to exit early.

Upvotes: 1

FullStack
FullStack

Reputation: 6020

Since you declared the function with a var it is scoped outside of methodDemo().

You could declare the function globally by removing var or move the demoFunction() code into methodDemo().

Upvotes: 0

Related Questions