我有一个Map<String, List<Future<Foo>>>
我想转换为 Map<String, List<Foo>>
(等待 future 完成)。目前,这是我执行操作的方式:
// source contains values with an async operation; convert to a map
final futures = source.map(
(k, v) => MapEntry(k, v.map((e) async => await e.asyncOperation())),
);
final json = {};
// works, but must wait for each entry to process
for (final kvp in futures.entries) {
json[kvp.key] = await Future.wait(kvp.value);
}
这将阻止每个条目子列表,有没有办法生成正确的 Map<String, List<Foo>>
同时等待所有内部列表 future ?
我可以await Future.wait(futures.values.flattened);
,但是我如何将结果重新分配回正确的 map 键?
最佳答案
立即完成所有 future 的一个原因是它们已经存在,如果您不立即等待所有 future,其中一个可能会在完成时出现(未处理!)错误,这很糟糕。
一次等待多个 future 的标准提供方法是 Future.wait
,需要 Iterable<Future<X>>
并返回 Future<List<X>>
.
这将直接帮助您处理各个列表,但随后您将得到一个 Future<List<Foo>>
map 中的每个键。您还必须将它们转换为列表。
所以,也许是这样的:
Future<Map<String, List<Foo>>> waitAll(
Map<String, Iterable<Future<Foo>>> map) async =>
Map.fromIterables(map.keys.toList(), await Future.wait(map.values.map(Future.wait));
关于dart - 我如何才能同时等待嵌套在 map 内的多个 future?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71211519/