6

How to exit in a loop of object in Firebase after a certain condition. I tried using return false but it doesn't work. Can someone help me. Thanks in advance.

Here is my code:

function checkRoom(room_id,user_id,other_user){


    var  dbRefObject = firebase.database().ref('chat-list');
    //getting all keys 
    dbRefObject.on('child_added', function (snap) {
        if(snap.key == 1){
            //if condition succeed the loop will exit
            return false; //but return false is not working here.
        }
    });
}

1 Answer 1

12

To break out of a snapshot's forEach iteration, you need to return true.

The forEach method's action parameter is:

A function that will be called for each child DataSnapshot. The callback can return true to cancel further enumeration.

Note that you can break out of the iteration by returning any truthy value - not just true.

Sign up to request clarification or add additional context in comments.

1 Comment

No worries. Note that the fact that any truthy value will break out of the iteration can lead to fun behaviour if you use arrow functions. For example, snapshot.forEach(item => items.push(item)) will break after the first push. You'd need to use snapshot.forEach(item => { items.push(item); }). Just something to be aware of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.