[英]Meteor 1.6 make synchronous call both client and server side
我目前在收集管理器上工作,该管理器还管理外键。 它还会生成一些表格,我很难检查外键并获取到客户端的正确回调。
我正在使用流星的wrapAsync方法,以便使用方法调用的同步版本。
首先,我要在“ check fk”方法中声明对函数的同步调用。
declareCheckFKMethod(index){
Meteor.methods({
[this._collectionList[index]._prefix.replace(/\//g,"")+this._checkFKSuffix]:(fk)=>{
var syncFunc = Meteor.wrapAsync(this.checkFKInDB.bind(this));
return syncFunc(fk,index)
}
})
}
这是目标函数:
checkFKInDB(fk,collectionIndex,callBack){
try{
var test = this._collectionList[collectionIndex].find({_id:fk}).fetch();
if(test.length==1){
return callBack(null,true);
}
else{
return callBack(null,false);
}
}
catch(e){
return callBack(new Meteor.Error("DB error", e.message),null)
}
}
然后在我的插入功能中,我检查客户端和服务器端的所有FK字段:
const check = Meteor.call(this._collectionList[index]._prefix.replace(/\//g,"")+this._checkFKSuffix,document[element.entryName]);
console.log(check)
这就是我插入有效文档时得到的:
服务器端控制台日志:true
客户端控制台日志:未定义
我怀疑客户端根本没有在等待回调,但是服务器却在等待。 我该如何解决? (顺便说一句,我尝试了await / async关键字,但这只会给我错误...)
您的客户端功能始终需要传递回调才能接收异步结果:
Meteor.call(this._collectionList[index]._prefix.replace(/\//g,"")+this._checkFKSuffix,document[element.entryName], (err, check) => {
console.log(err, check);
});
编辑:请注意,Meteor方法将解决Promise样式(更多有关Fibers工作原理的方法)中的值,而您的客户端将始终以回调样式接收结果或错误。 因此,在调用方法时在客户端上具有某种异步/等待样式模式的想法可能无法实现。
我实际上找到了一个解决方案,但是如果有人可以清楚地解释,我不确定为什么它可以工作:
我只需要制作一个“ checkFKInDB”服务器和客户端功能,如下所示:
checkFKInDB(fk,collectionIndex,callBack){
if(Meteor.isClient){
try{
var test = this._collectionList[collectionIndex].find({_id:fk}).fetch();
if(test.length==1){
return true;
}
else{
return false;
}
}
catch(e){
throw new Meteor.Error("DB error", e.message);
}
}
if(Meteor.isServer){
try{
var test = this._collectionList[collectionIndex].find({_id:fk}).fetch();
if(test.length==1){
return callBack(null,true);
}
else{
return callBack(null,false);
}
}
catch(e){
throw new Meteor.Error("DB error", e.message)
}
}
}
然后:
try{
test = Meteor.call(this._collectionList[index]._prefix.replace(/\//g,"")+this._checkFKSuffix,document[element.entryName]);
}
catch(e){
throw new Meteor.Error("DB error",e.message)
}
如果有人可以解释为什么需要在服务器端而不是客户端上进行回调,那就太好了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.