从未来实例中获取价值 [英] Getting values from Future instances

查看:73
本文介绍了从未来实例中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据是这样的:

{
  "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"
  }
}

我是我们可以执行以下功能:

I am using the following function:

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




  1. 我访问一名员工(以a <$ c(c>地图)从数据库(Firebase)

  2. 如果员工是领导者(具有关键的组)

  3. 我通过调用一个单独的函数,从数据库中获得了该组中每个员工的详细信息。

  4. 由于该函数返回的地图的值是 Future 的实例,因此我想从中提取实际值。为此,在地图上调用了 forEach
    但是,我仅将Future的实例作为值。

  1. I access an employee (as aMap) from the database (Firebase)
  2. If the employee is a leader (has a key "group")
  3. I get the details of each of the employee in the group filled up from the database by calling a separate function.
  4. Since the function returns a map with values that are instances of Future, I want to extract the actual values from them. For this a forEach is called on the map. However, I only get instances of Future as values.

如何获取实际值?

推荐答案

没有办法从异步执行恢复为同步执行。

There is no way to get back from async execution to sync execution.

要从期货获取值,有两种方法

To get a value from a Future there are two ways

将回调传递给 then(...)

theFuture.then((val) {
  print(val);
});

或使用 async / 等待以获得更好的语法

or use async/await for nicer syntax

Future foo() async {
  var val = await theFuture;
  print(val);
}

这篇关于从未来实例中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆