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?
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With