Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Async/await in List.forEach() in Dart

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.

like image 307
aelayeb Avatar asked Feb 26 '17 11:02

aelayeb


People also ask

Is forEach async Dart?

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.

How do you forEach in darts?

forEach() Function. Applies the specified function on every Map entry. In other words, forEach enables iterating through the Map's entries.

How does async await work Dart?

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 .

How do you break out of a forEach Dart?

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);


Video Answer


1 Answers

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}"); } 
like image 176
Stephane Avatar answered Oct 07 '22 17:10

Stephane