如何使用映射来触发异步请求但获得聚合结果?

时间:2016-11-10 14:48:17

标签: dictionary asynchronous dart

我有代码:

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方法。

1 个答案:

答案 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}

Plunker example