【发布时间】: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