user3013860
user3013860

Reputation: 77

await an anonymous function

In the following code I can't find a solution to await for the inner asynchronous code. The result is that the data is always returned empty. Any ideas?

Future<Map> resolveLinks(links) async {
  var data = {};

  (links as Map).forEach((k, v) async {

    switch (v["type"]) {
      case "address":
      data[k] = await getAddress(v["value"]);
        break;
      case "person":
        data[k] = await getPerson(v["value"], v["subtype"]);
        break;
    }
  });
  return data;
}

Upvotes: 2

Views: 3123

Answers (1)

julemand101
julemand101

Reputation: 31219

The reason why this won't work is because you inner function are returning Future objects you are never awaiting.

It should work if you modify your code to the following:

Future<Map> resolveLinks(links) async {
  var data = {};

  await Future.wait((links as Map).entries.map((entry) async {
    final k = entry.key;
    final v = entry.value;

    switch (v["type"]) {
      case "address":
        data[k] = await getAddress(v["value"]);
        break;
      case "person":
        data[k] = await getPerson(v["value"], v["subtype"]);
        break;
    }
  }));
  return data;
}

So instead of using forEach, I am using the map method on the entries iterable to map each entry into a Future object. When I takes all this Future objects and puts them into Future.wait which returns a Future there completes when all the other Future objects has returned its value.

Upvotes: 4

Related Questions