【问题标题】:Why Meteor js not execute serially on Meteor.call()为什么 Meteor js 不在 Meteor.call() 上串行执行
【发布时间】:2023-04-09 14:57:01
【问题描述】:

我对这个 Meteor.js 很陌生。在我的Template.myTemplate.onCreated() 中,我使用Meteor.call() 调用两个服务器方法。现在的问题是 Meteor.call() 回调中的代码在执行 onCreated 函数中的剩余代码后执行。 helpers 和 event 内部也发生了同样的事情。

对吗?还是我做错了什么?

如果是正确的,那么有什么办法可以让代码串行执行吗?

让你更好理解的例子:

client/myTemplate.js

Template.myTemplate.created = function(){
    console.log('created start');

    Meteor.call('myTestMethod1', function(err, res){
        if(res){
            console.log(res);
        }
    });

    Meteor.call('myTestMethod2', function(err, res){
        if(res){
            console.log(res);
        }
    });

    console.log('created end');
}

服务器/method.js

Meteor.methods({
    myTestMethod1 : function(){
        return "myTestMethod1";
    },

    myTestMethod2 : function(){
        return "myTestMethod2";
    }
});

控制台:

created start
created end
myTestMethod2
myTestMethod1

任何想法...

【问题讨论】:

  • 我建议你搜索“竞争条件”这个词。它可以帮助你发现你的代码在做什么以及为什么。
  • @Kyll race condition 是 two threads/control try to access the same data at the same time 我明白了...但是你认为 Meteor 这样做是为了防止 race condition ???
  • 好吧,当你有 API 调用时,竞争条件是一个永恒的问题。 Meteor 以多种方式解决它......在服务器上,使用 Fibers(以同步风格编写的异步代码)。在客户端,您可以使用反应变量。让我写一个答案。

标签: javascript meteor callback meteorite meteor-helper


【解决方案1】:

当您提供回调时,对 Meteor 方法的调用始终是异步的。请参阅official documentation。

如果您不提供回调,则调用将是同步的,并且在调用完成之前不会执行您的其余代码。 但是您可能无法通过同步调用获得任何结果。

【讨论】:

  • Meteor 方法只在服务器上阻塞,来自客户端的调用永远不会阻塞。
  • @ErezHochman 你的意思是来自客户端的服务器 API 调用是同步发生的,并且在执行服务器方法时虽然它有一个回调,但函数的剩余代码运行然后回调运行。跨度>
【解决方案2】:

解决此问题的一种方法是使用反应变量(或字典,例如 Session)来了解调用何时完成。因此,

Session.set('method1Completed', false);
Session.set('method2Completed', false);

Template.myTemplate.onCreated(function() { //Note that you should use onCreated now
  Meteor.call('method1', function() {
    Session.set('method1Completed', true); //You could also put your result here
  });
  Meteor.call('method2', function() {
    Session.set('method2Completed', true);
  });

  Tracker.autorun(function(computation) {
    if(Session.get('method1Completed') && Session.get('method2Completed')) {
      //If we get in here it means both methods have completed
      computation.stop(); //We're done, stop observing the variables
      doStuff();
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2017-10-03
    相关资源
    最近更新 更多