Meteor method call comes back as undefined

I have the following meteor methods defined in my Server code:

var lastClick = 0;
Meteor.methods({
  getLastClick: function(){
return lastClick;
},
setLastClick: function(clickedNow){
  lastClick = clickedNow;
}
});

I am trying to call the “getLastClick” method like this:

console.log("last click: "+Meteor.call('getLastClick'));

and it comes back as:

last click: undefined

What am I doing wrong here?

Thanks!

1 Like

You are calling from the client where it calls meteor methods as asynchronous functions which is why you are getting the results back undefined before they are being executed.

What suggestions do you have?

See:

I tried this techinque with the following:

console.log("last click: "+Meteor.apply('getLastClick', [], { returnStubValue: true }));

It still comes back as undefined

just call it normaly

Meteor.call('getLastClick', function(error, result) {
   console.log("last click: "+result)
})
1 Like

returnStubValue is for returning the value of the stub (i.e. the client-side method code). If you define your method on the server only, there is no stub, hence an undefined returned value. For getting the returned value from the server code, see @shock’s post.

I am calling it from an event helper:

var lastClick = Meteor.call('getLastClick', function(error, result) {
  console.log("last click-----: "+result)
})

 console.log("last click: "+lastClick);

which comes back as:

last click-----: 0
last click: undefined

I am assuming this is a scope issue. How can put the value on the call into the lastClick variable?

You are calling a method on a remote server.
This is asynchronous by nature.

Meteor.call sends a message to the server, and then returns immediately. It does NOT wait for the response.
So the return value of Meteor.call is undefined.

That’s why you must provide a callback.
When Meteor receive the response from the server, it calls your callback and you have the value from the server.

So you must define “var lastClick = null” before you execute Meteor.Call, and set its value INSIDE the callback with “lastClick = result”

Please, read the doc http://docs.meteor.com/#/full/meteor_call

I have gone through the documentation as you suggested and implemented the change as you suggested too, but it is still coming back as undefined…

var lastClick = null;
Meteor.call('getLastClick', function(error, result) {
  lastClick = result;
  console.log("Call back-----: "+lastClick)
})

assign them to session or reactVar if you want your value become reactive

Thanks everyone. After getting it going and using sessions, I am trying to do this using collections…

Do synchronous server methods not block when called from the client? Then how to get a non-reactive return value from a Meteor method without resorting to session vars?