2015-09-16 159 views
0

多次调用我需要调用3次相同的服务器的方法用不同的参数:流星:以异步服务器方法

// client code 
    var types = ['type1', 'type2', 'type3']; 
    for (var i = 0; i < types.length; i++) { 
    console.log('client calling', types[i]) 
    Meteor.call('myMethod', types[i], function (error, result) { 
     console.log('client got', types[i]) 
     Session.set(types[i], result.data); 
    }); 
    } 

    // server code 
    var Future = Npm.require("fibers/future"); 

    Meteor.methods({ 
    myMethod: function (type) { 
     var params = { 
     type: type 
     }; 

     var future = new Future(); 
     console.log('server calling', type) 
     HTTP.call("GET", Meteor.App.HOST + "/myApi", 
     {params: params}, function (error, results) { 
      if (error) { 
      future.throw(error); 
      } else { 
      console.log('server got', type) 
      future.return(results); 
      } 
     }); 

     return future.wait(); 
    } 
    }); 

服务器HTTP调用需要长达10秒。看看我看到的日志:

// client 
client calling type1 
client calling type2 
client calling type3 
client got type1 
client got type2 
client got type3 

// server 
server calling type1 
server got type1 
server calling type2 
server got type2 
server calling type3 
server got type3 

客户端日志是确定的。我期望在服务器上有相同的行为,但似乎一个客户端所做的调用是按顺序执行的。如果我启动两个客户端,我有以下服务器日志:

// server 
server calling type1 
server calling type1 
server got type1 
server calling type2 
server got type1 
server calling type2 
server got type2 
server calling type3 
server got type2 
server calling type3 
server got type3 
server got type3 

这是限制还是我的代码不正确?

+1

看起来像正常的异步行为。你为什么认为这是不正确的?你期待什么行为?即使在您的单个客户端情况下,如果其中一个HTTP GET需要很长时间,Meteor.call()的结果可能会失序返回。顺便说一句,你为什么用HTTP GET调用你自己的服务器? –

+0

@Fabrizio你需要在流星法里面使用'this.unblock()'http://docs.meteor.com/#/full/method_unblock –

+0

@MarkUretsky非常感谢! 'this.unblock()'正是我需要的。 –

回答

1

this.unblock()一个方法调用内部会解决这个问题,它不会阻止流星方法是好,当你做了一些API调用,发送电子邮件和真的没有等待它完成

在方法调用中调用。允许来自此 客户端的后续方法开始在新光纤中运行。 http://docs.meteor.com/#/full/method_unblock