我的数据是这样的:
{
"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"
}
}
我正在使用以下功能:
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;
}
Map
)
Future
的实例,我想从中提取实际值。为此,在地图上调用forEach
。
但是,我只将Future的实例作为值。 我如何获得实际值?
答案 0 :(得分:13)
无法从异步执行中恢复同步执行。
要从Future
获取值,有两种方法
将回调传递给then(...)
theFuture.then((val) {
print(val);
});
或使用async
/ await
获取更好的语法
Future foo() async {
var val = await theFuture;
print(val);
}
答案 1 :(得分:1)
您不是在等待await value
表达式完成。
forEach
调用遍历映射条目并为每个条目启动异步计算。然后删除该计算的未来,因为forEach
不使用其函数的返回值。
然后在任何异步计算完成之前返回映射,因此映射中的值仍然是期货。他们最终将改为非期货,但你不知道什么时候完成。
而不是forEach
来电,请尝试:
await Future.wait(groupMapWithDetails.keys.map((key) async {
groupMapWithDetails[key] = await groupMapWithDetails[key];
});
这将对映射中的每个键执行异步操作,并等待它们全部完成。之后,地图应具有非未来值。