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!
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.
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).
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 .
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.
You can also use Future.forEach with a map like this :
await Future.forEach(myMap.entries, (MapEntry entry) async {
await myAsyncFunc();
});
callFunc();
You could also use map
like:
const futures = myMap.map((a, b) => myAsyncFunc());
await Future.wait(futures);
callFunc();
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