从Future实例获取值

Hes*_*esh 5 dart dart-async

我的数据是这样的:

{
  "five": {
    "group": {
      "one": {
        "order": 2
      },
      "six": {
        "order": 1
      }
    },
    "name": "Filbert",
    "skill": "databases"
  },
  "four": {
    "group": {
      "three": {
        "order": 2
      },
      "two": {
        "order": 1
      }
    },
    "name": "Robert",
    "skill": "big data"
  },
  "one": {
    "name": "Bert",
    "skill": "data analysis"
  },
  "seven": {
    "name": "Colbert",
    "skill": "data fudging"
  },
  "six": {
    "name": "Ebert",
    "skill": "data loss"
  },
  "three": {
    "name": "Gilbert",
    "skill": "small data"
  },
  "two": {
    "name": "Albert",
    "skill": "non data"
  }
}
Run Code Online (Sandbox Code Playgroud)

我使用以下功能:

  Future retrieve(String id) async {
    Map employeeMap = await employeeById(id); //#1
    if (employeeMap.containsKey("group")) { //#2
      Map groupMap = employeeMap["group"];
      Map groupMapWithDetails = groupMembersWithDetails(groupMap); #3
      // above returns a Mamp with keys as expected but values 
      // are Future instances.
      // To extract values, the following function is
      // used with forEach on the map
      futureToVal(key, value) async { // #4
        groupMapWithDetails[key] = await value; 
      }
      groupMapWithDetails.forEach(futureToVal); // #4
    }
    return groupMapWithDetails;
   }
Run Code Online (Sandbox Code Playgroud)
  1. Map从数据库(Firebase)访问员工(作为a )
  2. 如果员工是领导者(有一个关键的"组")
  3. 通过调用单独的函数,我可以从数据库中获取组中每个员工的详细信息.
  4. 由于函数返回的值是实例的值Future,我想从中提取实际值.为此forEach,在地图上调用a .但是,我只将Future的实例作为值.

我怎样才能得到实际值?

Gün*_*uer 21

无法从异步执行返回到同步执行.

要从中获取值,Future有两种方法

传递一个回调 then(...)

theFuture.then((val) {
  print(val);
});
Run Code Online (Sandbox Code Playgroud)

或者使用async/ await用于更好的语法

Future foo() async {
  var val = await theFuture;
  print(val);
}
Run Code Online (Sandbox Code Playgroud)

  • 真的没有办法访问 Dart Future<Type> 的值吗?类似于 SCALA 的 `Await.result(someFuture, 5.seconds)` ??? (2认同)