我有一个Seq[String]
,需要这些字符串值来调用另一个定义为:
def getSomethingById(id: String): Future[Someting]
我尝试创建一个取Seq[String]
并返回Future[Seq[Something]]
的函数;即,
def getSomethings(ids: Seq[String]): Future[Seq[Something]]
获取Something
类型的唯一方法是调用上面的getSomethingById
方法。
我可以通过Seq[String]
映射,然后拨打getSomethingById
吗?
答案 0 :(得分:4)
您可以使用Future.sequence
:
def getSomethings(ids: Seq[String]): Future[Seq[Something]] =
Future.sequence(ids.map(getSomethingById))
https://www.scala-lang.org/api/current/scala/concurrent/Future%24.html
Future.traverse的简单版本。异步和非阻塞 将TraversableOnce [Future [A]]转换为 未来[TraversableOnce [A]]。用于将许多期货减少为一个 单一的未来。
答案 1 :(得分:0)
除现有答案外,您还可以使用非常相似的Future.traverse
scala> import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def getSomethingById(id: String): Future[String] = Future{
id + "from Something Id"
}
def getSomethings(ids: Seq[String]): Future[Seq[String]] =
Future.traverse(ids)(getSomethingById)
scala> getSomethingById: (id: String)scala.concurrent.Future[String]
scala> getSomethings: (ids: Seq[String])scala.concurrent.Future[Seq[String]]
scala> getSomethings(Range.apply(1,3).map(_.toString))
res0: Vector(1from Something Id, 2from Something Id)