Break loop in Firebase with Javascript

I am a beginner Firebase and am having trouble breaking the loop. The code below looks at the recipe products and the quantity of products, if the inventory has enough products to make the recipe, the code triggers an alert stating that there are enough products, otherwise it triggers the alert saying that the products in stock are not enough. I would like to break the loop from the else, how can I do?

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;
        }

    }

});

Upvotes: 1

Views: 674

Answers (1)

Ravi Shankar Bharti
Ravi Shankar Bharti

Reputation: 9268

If you want to stop listening the child_added event, you can try Off.

Try this:

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
        }

    }

});

For more information on off Please Read firebase References#off Documentation

Upvotes: 3

Related Questions