【发布时间】:2018-02-07 17:51:12
【问题描述】:
我有以下场景:
-
List[Building]收藏我会打电话给buildings -
def getAddress(building: Building): Future[Address]函数 - 结果应该是
List[BuildingWithAddress]集合
我想遍历List[Building] 并为每个元素调用getAddress 并等待它完成,以便我可以创建一个BuildingWithAddress 类型的新对象并将其存储在一个集合中,然后我将返回给调用者。
我以为我会使用理解,但事实证明,类似的东西不会真正起作用:
for {
building <- listOfBuildings
address <- getAddress(building)
buildingWithAddress = BuildingWithAddress(name = building.name, town = address.town)
} yield buildingWithAddress
我还考虑过使用flatMap 来遍历列表,然后对地址执行相同操作,但类型不同,它不起作用。
我尝试使用forEach,但又一次 forEach 没有等待 Future 完成。
这样一个简单的用例有什么解决方案?
【问题讨论】: