2015-07-06 53 views
0

我在这个Meteor.js中很新。在我的Template.myTemplate.onCreated()里面,我使用Meteor.call()调用两个服务器方法。现在问题是在Meteor.call()中执行回调函数中的代码,在执行onCreated函数内的剩余代码后执行。同样的事情发生在帮手事件为什么Meteor js不能在Meteor.call上串行执行()

是不是?或者我做错了什么?

如果它是正确的,那么有什么办法可以做代码将连续执行?

实例让你更好地理解:

客户端/ 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 

有什么想法...

+0

我建议你搜索单词“竞赛条件”。它可以帮助你发现你的代码正在做什么以及为什么。 –

+0

@Kyll ** race condition **是'两个线程/控件试图同时访问同一个数据',我知道它......但是你的想法和流星一样是为了防止**竞争条件** ??? – iamhimadri

+0

好吧,当你有API调用时,竞争条件是一个永久的问题。 Meteor以多种方式解决它...在服务器上,使用Fibres(异步代码以同步样式编写)。在客户端上,您可以使用无功变量。让我写一个答案显示它。 –

回答

0

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

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

+0

流星方法仅在服务器上阻塞时,来自客户端的呼叫永远不会阻塞。 –

+0

@ErezHochman您的意思是客户端的服务器API调用是同步发生的,并且在执行服务器方法时发生,尽管它有一个回调函数的剩余代码,然后运行回调函数。 – iamhimadri

0

解决此问题的一种方法是使用反应变量(或字典(如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(); 
    } 
    } 
}