【问题标题】:Meteor: multiple calls to async server methodMeteor:多次调用异步服务器方法
【发布时间】:2015-09-18 22:14:02
【问题描述】:

我需要用不同的参数调用 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

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

【问题讨论】:

  • 看起来像正常的异步行为。为什么你认为这是不正确的?你期待什么行为?即使在您的单个客户端情况下,如果其中一个 HTTP GET 需要很长时间,Meteor.call() 的结果也可能会出现乱序。顺便问一下,你为什么用 HTTP GET 调用你自己的服务器?
  • @Fabrizio 你需要使用内部流星方法this.unblock()docs.meteor.com/#/full/method_unblock
  • @MarkUretsky 非常感谢! this.unblock() 正是我所需要的。
  • @FabrizioFortino 没问题,如果有人也需要此信息,我会将其添加为答案。

标签: javascript asynchronous meteor


【解决方案1】:

在方法调用中this.unblock()会解决这个问题,它不会阻塞meteor方法,当你做一些API调用,发送电子邮件时很好,不用等待它完成

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    相关资源
    最近更新 更多