Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list.forEach doesn't await properly in async method

When using await in a forEach, the code doesn't await, and keeps executing the code after the forEach, but, when using a normal for, it awaits properly, se the following snippet:

Future<void> uploadTexts(List<String> someTexts) async {
    for(int i = 0; i < someTexts.length ; i++) {
      var text = someTexts[i];
      if (text  != null) {
        await uploadText(text);
      }
    }
    print("THIS PRINTS AFTER THE FOR IS DONE");
  }
Future<void> uploadTexts(List<String> someTexts) async {

 someTexts.where((text) => text != null).forEach((text) async{
    await uploadText(text);
  });
  print("THIS PRINTS BEFORE THE FOREACH IS DONE");
}

The first sample will print after the for is finished, while the second example will print before the for is finished.

Am I doing something wrong?

like image 936
Max.Moraga Avatar asked Feb 06 '26 09:02

Max.Moraga


1 Answers

When you use for you perform some action n times in your code, so every await works as expected. With forEach you start some operation to every element of list and continue to do following code, so in this case you don't wait for result of await

UPD:

Here is solution for forEach:

Future<void> uploadTexts(List<String> someTexts) async {
  List<String> filtered = someTexts.where((text) => text != null);
  await Future.forEach(filtered, (text) async {
    await uploadText(text);
  });
  print("THIS PRINTS BEFORE THE FOREACH IS DONE");
}
like image 125
Andrey Turkovsky Avatar answered Feb 09 '26 08:02

Andrey Turkovsky