示例代码
Map<String,String> gg={'gg':'abc','kk':'kojk'};
Future<void> secondAsync() async {
await Future.delayed(const Duration(seconds: 2));
print("Second!");
gg.forEach((key,value) async{await Future.delayed(const Duration(seconds: 5));
print("Third!");
});
}
Future<void> thirdAsync() async {
await Future<String>.delayed(const Duration(seconds: 2));
print('third');
}
void main() async {
secondAsync().then((_){thirdAsync();});
}
Run Code Online (Sandbox Code Playgroud)
输出
Second!
third
Third!
Third!
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我想用来等待地图的 foreach 循环完成然后我想打印third
预期的输出
Second!
Third!
Third!
third
Run Code Online (Sandbox Code Playgroud)
jam*_*lin 14
Iterable.forEach
, Map.forEach
, 和Stream.forEach
旨在对集合的每个元素执行一些代码以产生副作用。它们采用具有void
返回类型的回调。因此,这些.forEach
方法不能使用 callbacks返回Future
的任何值,包括返回的s。如果提供一个函数返回一个Future
,那Future
将会丢失,并且您将无法完成时得到通知。因此,您不能等待每个迭代完成,也不能等待所有迭代完成。
不要.forEach
与异步回调一起使用。
相反,如果您想按顺序等待每个异步回调,只需使用普通for
循环:
for (var mapEntry in gg.entries) {
await Future.delayed(const Duration(seconds: 5));
}
Run Code Online (Sandbox Code Playgroud)
(一般来说,我建议for
.forEach
在除特殊情况外的所有情况下都使用正常循环。Effective Dart 有一个大致相似的建议。)
如果您真的更喜欢使用.forEach
语法并希望Future
连续等待每个语法,则可以使用Future.forEach
(确实需要返回Future
s 的回调):
await Future.forEach([
for (var mapEntry in gg.entries)
Future.delayed(const Duration(seconds: 5)),
]);
Run Code Online (Sandbox Code Playgroud)
如果你想让你的异步回调可能并行运行,你可以使用Future.wait
:
await Future.wait([
for (var mapEntry in gg.entries)
Future.delayed(const Duration(seconds: 5)),
]);
Run Code Online (Sandbox Code Playgroud)
如果尝试使用异步函数作为 a或回调(以及许多类似 StackOverflow 问题的列表),请参阅https://github.com/dart-lang/linter/issues/891以获取分析器警告请求。Map.forEach
Iterable.forEach
归档时间: |
|
查看次数: |
3542 次 |
最近记录: |