0

What I am doing is taking the invoices first to get their id and from there in another collection with a query I get the items that belong to that invoice and push it into the array.

When an array is filled from a promise, it is shown as "empty" although it is not, since what is opened from the console shows if it has content (Images 1 2). And this is inside an asynchronous function (you shouldn't have problems with load times).

Async FetchItemsFromBills function

let billItems = []

const snapBills = await db.collection('bills').get()

await snapBills.forEach(async x => {
   const snaps = await db.collection('items').where('billId', '==', x.id).get()     
      snaps.forEach(item => 
         billItems.push({
           ...item.data(),
           _id: item.id
         }))
      })

   console.log('Items', billItems);
   console.log('Items Length', billItems.length);

enter image description here

enter image description here

Andres Gaibor
  • 133
  • 1
  • 8
  • @Andreas The [duplicate] is wrong, my post is not similar to the other, I am using an asynchronous function but even so, I receive an "empty" array, but the devtools console does appear full, while in another post it appears undefined because you are not using an asynchronous function, promises or callbacks – Andres Gaibor Jul 06 '20 at 07:42
  • 2
    I would still say that the dupe was (at least partly) correct. But your specific problem is, that `.forEach()` doesn't return anything that you could `await` for. Use `.map()` and `Promise.all()` – Andreas Jul 06 '20 at 07:50
  • [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Andreas Jul 06 '20 at 07:54
  • The `.map()` property does not exist in the firestore snapshots and I am having problems when I use _async/await_ in the innermost forEach, there it does return an **empty array** – Andres Gaibor Jul 06 '20 at 08:06
  • 1
    _"A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects representing the results of a query. **The documents can be accessed as an array via the `docs` property** or enumerated using the forEach method."_ ([Source](https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot)) – Andreas Jul 06 '20 at 08:17

0 Answers0