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!
Use a for loop over Map.entries instead of forEach. Provided you are in an async function, await-ing in the body of a for loop will pause the iteration. The entry object will also allow you to access both the key and value.
Future<void> myFunction() async {
for (var entry in myMap.entries) {
await myAsyncFunction(entry.key, entry.value);
}
callFunc();
}
You could also use map
like:
const futures = myMap.map((a, b) => myAsyncFunc());
await Future.wait(futures);
callFunc();
entries used in extract Maplist from HashMap.
products.entries.forEach((e) {
var key = e.key;
var values = e.value;
double sum = 0;
values.forEach((value) => sum += value[PlanogramShelf.SHELF_FULL]);
target.add(OrdinalSales(
key, double.parse((sum / valueslength).toStringAsFixed(2))));
});
You can also use Future.forEach with a map like this :
await Future.forEach(myMap.entries, (MapEntry entry) async {
await myAsyncFunc();
});
callFunc();