0

I am having difficulty working with Meteor.call callbacks. I have defined a function which retrieves values from the server side; however, it does not return them to the template, in order to loop over them with an {{#each}} loop.

Here is the function:

search: function()  {
   Meteor.call('mySearchFunction', arg1, function(err, res) { 
     if (err) console.log(err); 
     else if(res) {
       console.log(res);  
       return res; 
     }
   }); 
 }

The console.log(res) shows me the data that I need, which is properly fetched with mySearchFunction, yet I am unable to pass it to the template handler, despite it being an array which may be iterated over. So I tried the following:

search: function()  {
   var s = Meteor.call('mySearchFunction', arg1, function(err, res) { 
     if (err) console.log(err); 
     else if(res) {
       console.log(res);  
       return res; 
     }
   }); 
   console.log(s); 
   return s; 
 }

And console.log(res) continues to display the requisite data, yet console.log(s) appears as undefined. I think this is because the async nature of meteor returns s before res gets a chance to be evaluated server-side. Either way, its strange that I cannot return data from a helper that I have stored in the helper function.

nmac
  • 610
  • 1
  • 10
  • 20

1 Answers1

3

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({
  search: function () {
    arg = Session.get('currentSearch');
    return ReactiveMethod.call('mySearchFunction', arg);
  }
});

I'm not sure what arg1 is in your original post so I'm using a session variable in my solution, but that should get you on the right track.

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 (such as a search).

Also see the section about helpers in this post.

David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • arg1 is just a string, not sure if that makes a difference, I'm trying out your solution now... – nmac Mar 30 '15 at 21:34
  • I solved my issue with an answer from the question that you referenced. +1 for that. – nmac Mar 30 '15 at 21:39