从馆藏内容衍生的期货

Futures Derived From Contents of Collection

想象一个 returns 和 Future 这样的函数。

def findById(Int id): Future[MyObject]

我有一个 ID 集合。

val ids = Vector(1,2,3)

迭代集合并为每个值并行调用函数以(有效地)生成这个的最惯用的方法是什么?

val result: Vector[Future[MyObject]] = Vector(findById(1), findById(2), findById(3))

我觉得简单的map就够了:ids.map(findById),或者更冗长的ids.map(id => findById(id))

考虑以下示例代码:

import concurrent.ExecutionContext.Implicits.global
import concurrent.duration._
import concurrent.{Await, Future}


def findById(id: Int): concurrent.Future[String] = concurrent.Future { Thread.sleep(3000); "OK" }
val ids = Vector(1,2,3)
val sequenced = Future.sequence(ids.map(findById)) // we sequence them so we can wait for one future of a collection, not collection of futures
Await.result(sequenced, 10.seconds) // you probably don't want to block normally, but this is for tests it should be resolved in about 3 seconds, so it runs in parallel

您可以在 REPL 中 运行 它(只需 运行 scala 并执行 :paste)。