我只想检查我将要插入的数据是否存在于我的Firebase上,如果是,我只想破坏add函数:
FBDB.addCampain=function (campain){
CampiansRef.once('value',function(snapshot){
snapshot.forEach(function(childSnapshot){
if(campain.Name==childSnapshot.val().Name){
console.log("campain allredy exists on the DB");
return false; //I want to break the addCampain function from here!
}
});
});
var newCampainRef = CampiansRef.push();
campain.id = newCampainRef.key();
newCampainRef.set(campain,function(error){
if(error){
console.log("an error occured the campain did not add to the DB, error:" ,+error);
return false;
}
else{
console.log("campain succssesfuly added to the DB");
return true;
}
});
};当前发生的情况是,即使该活动存在于数据库中,它仍然继续进行实际的添加代码。必须有一种方法来“破坏”匿名函数中的addCampain函数,或者甚至将“返回假”传递到主范围。
发布于 2015-06-25 16:37:02
如果添加几个console.log语句,您将能够看到代码是如何流动的:
console.log('1. starting call to Firebase');
CampaignsRef.once('value',function(snapshot){
console.log('3. for value from Firebase');
snapshot.forEach(function(childSnapshot){
console.log('4. inside childSnapshot');
if (campaign.Name==childSnapshot.val().Name){
console.log("campaign already exists on the DB");
return false;
}
console.log('5. done with snapshot.forEach');
});
});
console.log('2. we started the call to Firebase');输出将类似于:
1. starting call to Firebase
2. we started the call to Firebase
3. for value from Firebase
4. inside childSnapshot
4. inside childSnapshot
4. inside childSnapshot
5. done with snapshot.forEach这可能不完全是你所期望的。2.位于代码块的末尾,但它直接在1.之后触发,这是在开始的时候。这是因为on从Firebase启动数据的异步加载。因为这需要时间,所以浏览器会在代码块之后继续使用代码。一旦从Firebase的服务器下载了数据,它就会调用回调,您可以做您想做的事情。但到那时,最初的背景已经完成。
在JavaScript中,没有办法等待异步函数完成。虽然您可能很欣赏这种方式的存在,但是当您对Firebase的调用结束时,他们的浏览器会被锁定,这会让用户感到沮丧。
相反,您有两个选择:
我将在下面使用选项1,因为这是Firebase JavaScript SDK已经做的事情。
FBDB.addCampaign=function (campaign, callback){
CampaignsRef.once('value',function(snapshot){
var isExisting = snapshot.forEach(function(childSnapshot){
if(campaign.Name==childSnapshot.val().Name){
return true; // this cancels the enumeration and returns true to indicate the campaign already exists
}
});
callback(isExisting);
});
};你会引用这样的话:
FB.addCampaign(campaign, function(isExisting) {
console.log(isExisting ? 'The campaign already existed' : 'The campaign was added');
};请注意,从服务器加载所有活动以检查特定的活动名称是否已经存在是非常浪费的。如果您希望活动名称是唯一的,则最好按名称存储这些活动。
CampaignsRef.child(campaign.Name).set(campaign);https://stackoverflow.com/questions/31054852
复制相似问题