Stop/Break 从 .on("child_added".. 如果满足特定条件

Stop/Break out from .on("child_added".. if certain condition is met

好的,所以我设置工作的方式是这样的。

一旦新 child 添加到数据库 .on("child_added"... 就会像这样触发:

ref.on("child_added", function(snapshot, prevChildKey) {
   ...
}

其中 ref 是对 Firebase 的引用。此 child 包含与本地时间进行比较的时间戳,一旦发生某些重复事件,例如: timeFromFirebase < localTime 虽然这是真的,但我执行了某些操作。 我还有一个名为 canPerformAction 的变量,最初设置为 true,然后在 child_added 内设置为 false,因此我可以忽略其他传入的信号,直到我完成当前的动作,这里是

var canPerformAction = true;
ref.on("child_added", function(snapshot, prevChildKey) {
   if (!canPerformAction) return;
   canPerformAction = false;
   ...
}

现在我需要某种方法来打破 out/finish ref.on("child_added".. 如果 timeFromFirebase < localTime 变为假。在这种情况发生的同时,我将设置 canPerformAction = true 所以我现在正在接受新的 children 并且整个过程再次开始。

所以最后是这样的:

var canPerformAction = true;
   ref.on("child_added", function(snapshot, prevChildKey) {
   if (!canPerformAction) return;

   canPerformAction = false;

   //time is checked repeatedly, I simplified it to if statement here
   if (timeFromFirebase < localTime) {
      ...
   } else {
      canPerformAction = true;
         //Break out here
   }
}

相关来源:http://firebase.com

您想在添加子项时执行一些操作,并继续执行操作直到 timeFromFirebase < localTime 为 false。我认为 while 循环是你想要的。

ref.on("child_added", function(snapshot, prevChildKey) {
    while(timeFromFireBase >= localTime){
        //do some stuff
    }
}

编辑 - 如果你想使用 canPerformAction 标志,你可以像这样设置它,但我认为如果时间是唯一改变它的东西,则没有必要保留标志

canPerformAction = true
ref.on("child_added", function(snapshot, prevChildKey) {
    while(canPerformAction = true){
        if(timeFromFireBase < localTime){
            ...
        }else{
            canPerformAction = false;
        }
    }
}