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

旧街凉风 提交于 2019-12-19 10:49:23

问题


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


来源:https://stackoverflow.com/questions/52276412/how-to-avoid-using-await-key-in-dart-map-by-foreach-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!