Scala - 如何在映射 Seq 时调用未来函数?

Scala - How to call a future function while mapping over a Seq?

我有一个 Seq[String],需要这些字符串值来调用定义为的另一个函数:

def getSomethingById(id: String): Future[Someting]

我正在尝试创建一个接受 Seq[String] 和 returns Future[Seq[Something]] 的函数;即,

def getSomethings(ids: Seq[String]): Future[Seq[Something]]

获取Something类型的唯一方法是调用上面的getSomethingById方法。

有什么方法可以映射 Seq[String],然后调用 getSomethingById

您可以为此使用 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

Simple version of Future.traverse. Asynchronously and non-blockingly transforms a TraversableOnce[Future[A]] into a Future[TraversableOnce[A]]. Useful for reducing many Futures into a single Future.

除了现有答案,您还可以使用非常相似的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)