How to invoke a function in Meteor.methods and return the value

那年仲夏 提交于 2019-12-13 21:28:21

问题


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

回答1:


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



回答2:


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

});


来源:https://stackoverflow.com/questions/28547632/how-to-invoke-a-function-in-meteor-methods-and-return-the-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!