How to avoid using await key in dart Map by foreac

2020-03-04 02:47发布

问题:

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!

回答1:

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


回答2:

You could also use map like:

const futures = myMap.map((a, b) => myAsyncFunc());
await Future.wait(futures);
callFunc();


回答3:

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


回答4:

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

await Future.forEach(myMap.entries, (MapEntry entry) async {
  await myAsyncFunc();          
});
callFunc();