I'm writing some kind of bot (command line application) and I'm having trouble with async execution when I'm using the "forEach" method. Here is a simplified code of what I'm trying to do :
main() async { print("main start"); await asyncOne(); print("main end"); } asyncOne() async { print("asyncOne start"); [1, 2, 3].forEach(await (num) async { await asyncTwo(num); }); print("asyncOne end"); } asyncTwo(num) async { print("asyncTwo #${num}"); }
And here is the output :
main start asyncOne start asyncOne end main end asyncTwo #1 asyncTwo #2 asyncTwo #3
What I'm trying to get is :
main start asyncOne start asyncTwo #1 asyncTwo #2 asyncTwo #3 asyncOne end main end
If someone knows what I'm doing wrong I would appreciate it.
forEach<T> method Null safety Performs an action for each element of the iterable, in turn. The action may be either synchronous or asynchronous. Calls action with each element in elements in order.
forEach() Function. Applies the specified function on every Map entry. In other words, forEach enables iterating through the Map's entries.
Summary of asynchronous programming in Dart Asynchronous function is a function that returns the type of Future. We put await in front of an asynchronous function to make the subsequence lines waiting for that future's result. We put async before the function body to mark that the function support await .
You CAN empty return from a forEach to break the loop; List<int> data = [1, 2, 3]; int _valueToBePrinted; data. forEach((value) { if (value == 2) { _valueToBePrinted = value; return; } }); // you can return something here to // return _valueToBePrinted; print(value);
You need to use Future.forEach.
main() async { print("main start"); await asyncOne(); print("main end"); } asyncOne() async { print("asyncOne start"); await Future.forEach([1, 2, 3], (num) async { await asyncTwo(num); }); print("asyncOne end"); } asyncTwo(num) async { print("asyncTwo #${num}"); }
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