Web services 从Scala foreach中的多个WS调用返回列表

Web services 从Scala foreach中的多个WS调用返回列表,web-services,scala,playframework-2.4,Web Services,Scala,Playframework 2.4,我正在对返回用户连接列表的服务进行WS-call。收到响应后,我在列表上执行foreach,并在foreach中对另一个服务进行WS调用,以获取每个连接的更多详细信息 目前我正在尝试使用ListBuffer,但由于调用的异步性质,在收集详细信息之前,它将返回空 我的代码如下,它向我的控制器返回一个空的列表: def getAllConnections(username: String) = { connectionsConnector.getAllConnections(username

我正在对返回用户连接列表的服务进行WS-call。收到响应后,我在列表上执行
foreach
,并在
foreach
中对另一个服务进行WS调用,以获取每个连接的更多详细信息

目前我正在尝试使用
ListBuffer
,但由于调用的异步性质,在收集详细信息之前,它将返回空

我的代码如下,它向我的控制器返回一个空的
列表

def getAllConnections(username: String) = {
    connectionsConnector.getAllConnections(username).map {
      connections =>
        val connectionsList: ListBuffer[ConnectionsResponse] = ListBuffer()
        connections.map {
          connection =>
            usersService.getUser(connection.connectionUsername).foreach {
              case Some(user) =>
                val blah = ConnectionsResponse(user, connection)
                connectionsList.+=(blah)
            }
        }
        connectionsList.toList
    }
  }

关于如何将
未来[List]
返回控制器的任何建议都将非常好,谢谢。

使用单子for循环:

def getAllConnections(username: String) = connectionsConnector.getAllConnections(username) map { connections ->
    for {
      connection  <- connections
      user        <- usersService.getUser(connection.connectionUsername)
    }
    yield ConnectionsResponse(user, connection)
}
def getAllConnections(用户名:String)=connectionsConnector.getAllConnections(用户名)映射{connections->
为了{
连接<代码>用于{
连接(u,c))}
}获取usersWithConnection.collect{case(某些(用户,连接)=>ConnectionsResponse(用户,连接)}
至少应该给你一些想法。我们可以在未来的上下文中使用a进行理解。future.traverse将未来列表转换为列表的未来。需要与用户一起返回连接会增加额外的复杂性,但我们可以只映射单个未来,以包括与用户的连接

for {
  connections <- connectionsConnector.getAllConnections(username)
  usersWithConnection <- Future.traverse(connections){ c =>  userService.getUser(c.connectionUsername).map(u => (u,c))  }
} yield usersWithConnection.collect{ case (Some(user), conn) => ConnectionsResponse(user, conn)}