2017-01-10 32 views
1

我是初學者Firebase,無法打開循環。下面的代碼會查看配方產品和產品數量,如果庫存有足夠的產品來製作配方,則代碼會觸發警報,指出有足夠的產品,否則會觸發警報,說明庫存產品不是足夠。我想從其他方面打破循環,我該怎麼辦?使用Javascript在Firebase中斷開循環

checkFirebase.orderByKey().limitToLast(20).on('child_added', function(snapshot){ 

    var productRecipe = snapshot.key; 
    var amountRecipe = snapshot.child("amount").val() * amountAdded; 

    if(productRecipe == productStock){ 

     if(amountRecipe <= amountStock){ 
      alert("The amount is enough."); 
     }else{ 
      alert("The quantity is not enough."); 
      break; 
     } 

    } 

}); 
+1

有這個代碼不循環,所以'break'什麼都不會做。你期望它打破了什麼? –

+0

當代碼流進入else時,我希望它流轉到另一個地方。 Firebase中的異步通信遇到了很多問題。我仍然不明白。 @FrankvanPuffelen –

回答

2

如果要停止監聽child_added事件,你可以嘗試Off

試試這個:

checkFirebase.orderByKey().limitToLast(20).on('child_added', function(snapshot){ 

    var productRecipe = snapshot.key; 
    var amountRecipe = snapshot.child("amount").val() * amountAdded; 

    if(productRecipe == productStock){ 

     if(amountRecipe <= amountStock){ 
      alert("The amount is enough."); 
     }else{ 
      alert("The quantity is not enough."); 
      checkFirebase.off('child_added');//stop listening to child_added event 
     } 

    } 

}); 

欲瞭解更多信息,請off閱讀firebase References#off Documentation

+0

你確定它是'checkFirebase' ref,你可以調用'off'而不是'limitToLast'返回的ref? – cartant

+0

如果您在'checkFirebase'上調用'off',它將停止監聽'checkFirebase'引用中的任何child_added,你想要那個還是其他的東西? –

+0

只是這不是'on'被調用的引用,因爲'limitToLast'返回一個帶有限制的引用。看起來不正確,就是這樣。 – cartant