2016-12-11 86 views
0

Meteor.call中的Async回调不会等待Meteor.method的结果。这是代码。Meteor.call不会等待结果

Meteor.call("fetchData",function (err,res) { 
     if (err){ 
      console.log("error ", err); 
     }else { 
      console.log("success ", res); 
      return res; 
     } 
    });//calling this from onRendered of client/somejs.js 

这里是方法

fetchData :function(){ 
     HTTP.call("POST","http://localhost:8080",{ 
      data:'{"apple":"grape"}' 
     },function (err,res) { 
      if (err){ 
       console.log("error ", err); 
      }else { 
       console.log("success ", res); 
       return res; 
      } 
     }) 
    }//Server/methods.js 

当Meteor.call被触发时,我得到的服务器上的日志作为success与它的结果。 在客户端我得到success undefined。 客户端的调用不会等待结果。我也尝试在服务器上执行Fibers和Synchronous。它不适用于我。在这种情况下,发布被阻止(我猜是由于API调用)。

另一件事是,我试图用DB查询而不是API调用相同。这工作正常。我从方法得到的结果。

我在哪里出错了。帮助。

谢谢

回答

1

Sanjith。

您的期货走在了正确的道路上。默认情况下,Meteor的方法是异步的,所以客户端需要一些“等待”机制。为此,我建议使用Meteor.wrapAsync或Promises。这里是实现两个两个详细的解释:

https://themeteorchef.com/snippets/synchronous-methods/#tmc-using-wrapasync

https://themeteorchef.com/snippets/promise-based-modules/#tmc-calling-our-promise-based-module-from-the-client

第二个环节是更侧重于构造使用承诺你的代码,但给出了如何调用依赖的方法一个很好的演示一个承诺的回应。

+0

但为什么在数据库查询的情况下做同样的工作?我有一个方法,检查用户名是否已经存在。这工作正常,我收到客户端的Meteor.call.Btw结果将检查出链接。我对JS很新颖。 –