2016-11-14 64 views
0

我是JavaScript新手,我不理解如何等待Meteor.call方法的结果。 这是我的代码在客户端等待Meteor.call结果

 //client/main.js 
    //Added the callback 
     Template.hello.events({ 
    'click button'(event, instance) { 
    // increment the counter when button is clicked 
    instance.counter.set(instance.counter.get() + 1); 
    var res = Meteor.call("callMeLater","sanj",function (err,res) { 
     if (err) { 
     console.log(err); 
     } else { 
     console.log("this is the result main ", res); 
     } 
    }); 
    console.log("this is the result ", res); 
    } 
     //server/main.js 
     Meteor.methods({ 
     callMeLater :function (name) { 
      var callMeLaterSync =Meteor.wrapAsync(callMeLaterAsync); 
      var result = callMeLaterSync(name); 
      console.log("this is the test", result); 
      return result; 
     } 
    }); 


    var callMeLaterAsync = function (name,cb) { 
     setTimeout(function() { 
      cb && cb (null ,"hey there, "+name); 
     },2000); 
    }; 

在控制台上,我得到

this is the result undefined 

this is the result main hey there, sanj 

我怎么等待通过阻断在客户端执行的Meteor.call的结果。 请帮助

感谢

+0

你不想(也不能?)在客户端上阻塞。任何需要在Meteor.call之后需要执行的事情都需要在回调函数中执行(例如,您在执行'console.log(“this is the result main”,res);' – Adam

+0

因此,我使用Session或Reactive- var?使得接收到的结果得到反映。这是最好的解决方案吗? –

+0

我想你可能会感到困惑。代码中的两个“res”变量是完全独立的,你只能处理Meteor中的“res”。调用回调函数(例如,你正在做'console.log(“this is the result main”,res);')。你可以存储你想要的资源(在一个会话变量var或反应变量var中,或者只是一个典型的js var。你想用它做什么? – Adam

回答

0

只要把你的代码放到一个回调方法。

Meteor.call('callMeLater',"sanj", function(err, res){ 
    if (err) { 
     console.log(err); 
    } else { 
     console.log("this is the result ", res); 
    } 
    }); 
+0

我编辑了我的问题 –