我有代码:
import 'dart:async';
Future<int> expensiveCallFromALib(int value) async {
print('expensiveCall($value)');
return value + 1;
}
test() {
Map<String, int>input = {"one":1, "two":2};
Map result = {};
print("A");
input.forEach((String key, int value) {
expensiveCallFromALib(value).then((int value) {
result[key] = value;
});
print("B");
});
print("C");
print(result);
}
main() {
test();
}
...与输出
A
B
B
C
{}
expensiveCall(1)
expensiveCall(2)
... 但是我想要
A
B
expensiveCall(1)
B
expensiveCall(2)
C
{one: 2, two: 3}
关键是,我无法更改昂贵的CallFromALib方法。
最佳答案
test() async {
Map<String, int>input = {"one":1, "two":2};
Map result = {};
print("A");
for(final key in input.keys) {
int value = await expensiveCallFromALib(input[key]);
result[key] = value;
print("B");
}
print("C");
print('result: $result');
}
输出不是您想要的,但是我想它已经足够接近了;-)
HTML OUTPUT
CONSOLE
A
expensiveCall(1)
B
expensiveCall(2)
B
C
result: {one: 2, two: 3}
Plunker example
关于dictionary - 如何使用 map 触发异步请求但获得汇总结果?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40530436/