0

When I have a Future function that have nested future functions inside, the result doesn't wait for function to complete, here is a sample of code to get data from firestore:

Previous variables: DocumentReference idoc and List sids

Future<bool> check() async {

    bool result = true;

    await idoc.get().then((value) {
      if (!value.data['av']) {
        result = false;
      } else {
        sids.forEach((sid) async {
          DocumentReference jdoc = idoc.collection('items').document(sid);
          await jdoc.get().then((jdocValue) {
            if (!jdocValue.data['av']) {
              result = false;
            }
          });
        });
      }
    });
    return result;
}  

When I call check(), even using then:

check().then( (value) => print(value.toString()) );

I just get 'false' if the first check is true, I mean if "idoc.data['av']" in firestore is false, but, if this condition is false and I entered in the 'else' to evaluate each document inside 'items' collection, then if any of them is false I get 'true' calling check().

I want to wait for the hole evaluation of that function and get 'false' as a result to use it if any document of 'items' is false.

Sir Galan
  • 55
  • 5
  • `check().then(callback)` already invokes `callback` only after `check()` has completed executing. The reason why your `else` block isn't updating `result` the way you expect is because your `check()` function returns prematurely: `forEach` should not be used with asynchronous callbacks. See https://stackoverflow.com/a/63719805/. – jamesdlin Sep 19 '20 at 19:48
  • try using await instead of then, it will be much more clean code for you to understand – Omer Gamliel Sep 19 '20 at 20:15
  • BTW, not only would using a normal `for` loop instead of `forEach` fix your problem, but it would give you the additional flexibility of being able to `break` out of the loop early and avoid doing unnecessary work. – jamesdlin Sep 19 '20 at 20:25

0 Answers0