0

I got a nested query in an forEach loop which never gets executed. The first print statements does its work but the second is never called so I think there is some problem with async/await here. Can I use async/await in a forEach - loop?

final CollectionReference activityfeedRef =
    Firestore.instance.collection("activityfeed");

someFunction() async {
QuerySnapshot user = await userRef
            .document(locationId)
            .collection('user')
            .getDocuments();

        user.documents.forEach((doc) async {
          if (doc.exists) {
            var userId = doc['uid'];
            print("userId"); //This print statement works

            //Following query probably never gets executed
            QuerySnapshot activity = await 
            activityfeedRef
                .document(userId)
                .collection('items')
                .where('type', isEqualTo: 'comment')
                .where('locationId', isEqualTo: widget.locId)
                .getDocuments();

           print("DONE"); //The print statement does not work

            activity.documents.forEach((item) {
              if (item.exists) {
                print("Exists");

              } else {
                print("Does not exist");
              }
            });
          }
        });
      }

Anybody suggestions?

Juju
  • 439
  • 3
  • 18
  • `user.documents` is a Iterable? If yes, you can do a for, my suggestion: `for (int i = 0; i < user.documents.length; i++)` – Rocigno Medeiros Jun 03 '20 at 13:45
  • Are you sure there is more than one element in user.documents? – returnVoid Jun 03 '20 at 13:46
  • It depends on the locationId, 0-99 users can subscribe to a locationId. I tried the for loop as well but it does not work either. – Juju Jun 03 '20 at 13:51
  • Try using the other type of for Each for (item in user.documents) { /*code goes*/} – returnVoid Jun 03 '20 at 14:12
  • Can you give a code example? I just figured out that when I delete the "QuerySnapshot activity = await " the second print statement does print. But then I have no access to the documents. So I guess its waiting "for ever"? – Juju Jun 03 '20 at 15:48
  • what is activityfeedRef equal to? Also are you sure that the query will return a document? – Peter Haddad Jun 03 '20 at 16:21
  • updated my post regarding the activityfeedRef. I just manipulated the database in a way that there is a document which meets the conditions. So it theoretical should return a document. Even if there wasn't a document it should run the code and print "DONE", right? – Juju Jun 03 '20 at 16:28
  • Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Deniss T. Jun 05 '20 at 09:31

0 Answers0