Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid using await key in dart Map by foreach function

So, I have a map which has to do with some asynchronous processing using the items inside. I used the forEach loop construct and inside the callback is designed to be async because I call an await inside the iteration body

myMap.forEach((a, b) { await myAsyncFunc(); } );
callFunc();

I need the callFunc() to be called after all the items have been iterated. But the forEach exits immediately. Help!

like image 236
Vijay Kumar Kanta Avatar asked Sep 11 '18 12:09

Vijay Kumar Kanta


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.

Is forEach a map async?

The map function behaves exactly the same as forEach in terms of async operations, meaning all of the callbacks start at the same time and log exactly after 2 seconds. On top of this, the . map returns an array of promises, (one promise per execution, in the same order).

Why We Use await in Dart?

Summary of asynchronous programming in Dart 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 .

Is await blocking a flutter?

Await calls are non-blocking. The way this works is, while Dart is single-threaded, some Dart code delegate their implementation to the Dart VM. Things like file reads or HTTP requests are performed outside of Dart (either by the browser or in c++), in a different thread.


2 Answers

You can also use Future.forEach with a map like this :

await Future.forEach(myMap.entries, (MapEntry entry) async {
  await myAsyncFunc();          
});
callFunc();
like image 78
Jordan Alcaraz Avatar answered Sep 30 '22 22:09

Jordan Alcaraz


You could also use map like:

const futures = myMap.map((a, b) => myAsyncFunc());
await Future.wait(futures);
callFunc();
like image 41
Andrei Tătar Avatar answered Oct 01 '22 00:10

Andrei Tătar