[英]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.