How to break out of the querySnapshot forEach loop method?

Viewed 6057

I want to break out of a forEach loop. Consider this:

db.collection('users').get().then(querySnapshot => {
        if (!querySnapshot.empty) {
            querySnapshot.forEach(doc => {
                let data = doc.data()
                if (data.age == 16) {
                    break //this is not working
                }
            })
        }
    }
)

The documentation mentions nothing about breaking out the forEach loop

3 Answers

Instead of using forEach on QuerySnapshot directly, you could iterate its docs property instead, which is just a plain old javascript array. Write a for loop, which you can break as needed:

for (var i in querySnapshot.docs) {
    const doc = querySnapshot.docs[i]
    if (make_some_decision_here) {
        break
    }
}

.forEach does not provide a direct mechanism for early exits. Your best bet to achieve this would be to throw an exception:

querySnapshot => {
  if (!querySnapshot.empty) {

    try {

      querySnapshot.forEach(doc => {
          let data = doc.data()
          if (data.age == 16) {
              // Throw an exception to break. Use a custom exception type to
              // distinguish it from other possible exceptions that could be
              // thrown
              throw EarlyExit; 

          }
      })

    } catch(exception) {

      // If the exception thrown is not our EarlyExit type, then re throw,
      // otherwise resume as if look with terminated
      if(exception !== EarlyExit) {
        throw exception
      }
    }
  }
}

Alternatively, you could use the regular for-loop approach to allow for simpler look breaking:

for(const doc of querySnapshot) {
      let data = doc.data()
      if (data.age == 16) {
          break;
      }
}

According to here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

the only stop or break a forEach() loop is to throw an exception
Try these alternatives
A simple loop
A for...of loop
Array.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()

Related