0

I need to perform an operation after I retrieve all of the docs from firebase, but getDocs don't allow for .then.

There's a post that has an example but it's more than I think I need and I still don't understand how to implement the solution.

Here's the code:Using getDoc().then() inside of a loop Firebase

    const q = this.itineraryService.findData(filters);

    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      this.array.push({ ...doc.data(), id: doc.id});
    });

I'd like to be able to just add a .then to the last ) but it doesn't allow that. So how can I wait until I get all of the docs before performing the next operation.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
D.Hodges
  • 1,794
  • 4
  • 24
  • 47

1 Answers1

1

If you want to use then instead of await, that'd be:

getDocs(q).then((querySnapshot) => {
  querySnapshot.forEach((doc) => {
    this.array.push({ ...doc.data(), id: doc.id});
  });
});

This works because the getDocs function returns a Promise<QuerySnapshot>.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I want to wait until after the querySnapshot finishes retrieving all of the docs. – D.Hodges Nov 30 '22 at 01:14
  • That you already do with `await`. You can't reliably combine `await` and `then`. This sounds like a [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What isn't working about the code you shared that makes you think you need both `await` and `then`? Is there an error message? – Frank van Puffelen Nov 30 '22 at 01:15
  • You know...I think I see what I'm missing. Is this line actually retrieving all of the docs? const querySnapshot = await getDocs(q); I was under the assumption that the querySnapshot.forEach() is what I'd have to wait for but what I think you're saying is that all of the docs are already in querySnapshot, so there's not need to wait after that. – D.Hodges Nov 30 '22 at 01:36
  • How about the .forEach? I need to add data only to the 0 element after pushing all of the data to the array. Is forEach a synchronous action? Does it move to the next line of code before iterating over the snapshot? – D.Hodges Nov 30 '22 at 01:42
  • A `QuerySnapshot` contains a snapshot of the query results, so of the documents you requested. That's why that method returns a `Promise` and `forEach` or `doc.data()` (for example) do not. – Frank van Puffelen Nov 30 '22 at 04:46