如何通过foreach函数在Dart Map中避免使用等待键 [英] How to avoid using await key in dart Map by foreach function
问题描述
因此,我有一个映射,该映射与使用其中的项目进行的一些异步处理有关.我使用了forEach循环构造,并且在回调内部被设计为异步的,因为我在迭代体内调用了await.
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();
所有项目都经过迭代后,我需要调用callFunc().但是forEach立即退出.救命!
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();
}
这篇关于如何通过foreach函数在Dart Map中避免使用等待键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!