Reputation: 3200
Can you please tell me how I can invoke a function when I make a meteor method/call.
For test purposes and keeping it simple, I get a value of 'undefined' on the client console.
Server.js
Meteor.methods({
testingFunction: function() {
test()
}
});
function test(){
var name = 'test complete'
return name
}
client.js
Template.profile.events({
'click #button': function (event) {
event.preventDefault();
Meteor.call('testingFunction', function(error, response) {
if (error) {
console.log(error);
} else {
console.log(response);
}
});
}
});
Upvotes: 0
Views: 1041
Reputation: 316
Here is a great example:
Client Side:
// this could be called from any where on the client side
Meteor.call('myServerMethod', myVar, function (error, result) {
console.log("myServerMethod callback...");
console.log("error: ", error);
console.log("result: ", result);
if(error){
alert(error);
}
if(result){
// do something
}
});
Server Side:
// use Futures for threaded callbacks
Future = Npm.require('fibers/future');
Meteor.methods({
myServerMethod: function(myVar){
console.log("myServerMethod called...");
console.log("myVar: " + myVar);
// new future
var future = new Future();
// this example calls a remote API and returns
// the response using the Future created above
var url = process.env.SERVICE_URL + "/some_path";
console.log("url: " + url);
HTTP.get(url, {//other params as a hash},
function (error, result) {
// console.log("error: ", error);
// console.log("result: ", result);
if (!error) {
future.return(result);
} else {
future.return(error);
}
}
);
return future.wait();
}//,
// other server methods
});
Upvotes: 1
Reputation: 64312
Any function without a return
statement will return undefined
. In this case, you need to add return test()
to return the value of the call to test
from your method.
Meteor.methods({
testingFunction: function() {
return test();
}
});
Upvotes: 1