user3557972 user3557972 - 23 days ago 4
Dart Question

How to use a map to fire async request but get an aggregated result?

I have the Code:

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();
}


... with the output

A
B
B
C
{}
expensiveCall(1)
expensiveCall(2)


... but I want

A
B
expensiveCall(1)
B
expensiveCall(2)
C
{one: 2, two: 3}


The Point is, that I cant change the expensiveCallFromALib method.

Answer
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');
}

The output is not exactly how you want it but I guess it's close enough ;-)

HTML OUTPUT
CONSOLE
A
expensiveCall(1)
B
expensiveCall(2)
B
C
result: {one: 2, two: 3}

Plunker example

Comments