简体   繁体   中英

Why does for-each work, but for...of... doesn't?

This is my code to fetch data from firebase:

const querySnapshot = await db.collection('entries').get()

I want to add the data of every entry-element to a new array for which I got two ways to do it:

querySnapshot.forEach((entry) => {
   const entryData = entry.data()
   entries.value.push(entryData)
})

and

for (const entry of querySnapshot) {
      const entryData = entry.data()
      if (entry) { entries.value.push(entryData)
}

The first solution works, but the second throws this error: TypeError: "querySnapshot is not iterable" . Aren't the two ways basically doing the same? Why does on throw an error while the other doesn't?

A querySnapshot , which is what is returned from the get method, is not an array or an iterable.

https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot

forEach is a method from the querySnapshot object, which is why you can use it.

They are not the same. The first when simply means that your object has a forEach method.

The second one means that your object has a [Symbol.iterator] property which is a generator. This makes your object iterable.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator

As Alberto Rivera stated, the forEach is a QuerySnaphot method and it does the work for you. But you can loop from those documents yourself by using:

    const entries = await db.collection('entries').get();
    for (entry of entries.docs) {
        console.log(entry.id);
    }

Note that ".docs" comes with your querysnapshot and its is iterable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM