我在这个Meteor.js中很新。在Template.myTemplate.onCreated()
内,我使用Meteor.call()
调用两个服务器方法。现在问题是在onCreated函数中执行剩余代码后,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)
当您提供回调时,对Meteor方法的调用始终是异步的。请参阅official documentation。
如果您不提供回叫,则呼叫将是同步的,并且在呼叫完成之前,其余代码将不会执行。 但是你可能无法通过同步调用获得任何结果。
答案 1 :(得分: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();
}
}
}