如何在Meteor.methods中调用函数并返回值

时间:2015-02-16 18:05:14

标签: javascript function methods meteor

你能告诉我在制作流星方法/电话时如何调用一个函数。

出于测试目的并保持简单,我在客户端控制台上获得了'undefined'值。

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

2 个答案:

答案 0 :(得分:1)

任何没有return语句的函数都将返回undefined。在这种情况下,您需要添加return test()以从您的方法返回对test的调用值。

Meteor.methods({
  testingFunction: function() {
    return test();
  }
});

答案 1 :(得分:1)

这是一个很好的例子:

客户端:

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

服务器端:

// 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

});