来自收藏内容的未来

时间:2015-02-18 21:21:31

标签: scala future scala-collections

想象一个像这样返回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))

1 个答案:

答案 0 :(得分:1)

我认为简单的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)。