我有代码:
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}
Point是,我无法改变昂贵的CallFromALib方法。
答案 0 :(得分:0)
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}