动态创建以理解期货并等待完成

时间:2016-03-18 15:57:23

标签: scala for-comprehension

我有以下代码:

// Start async functions
val async1: Future[Seq[Int]] = ...
val async2: Future[Seq[Int]] = ...
val async3: Future[Seq[Int]] = ...

// Wait for completion
(for {
    a1 <- async1
    a2 <- async2
    a3 <- async3
} yield (a1, a2, a3)).map {
   // Use the results
}

我想改进它以处理可变数量的异步函数(并不一定每次调用它们)。到目前为止我所做的是:

// Start the async functions ?
val asyncs: Seq[Future[Seq[Int]] = otherList.filter(x => someCondition).map(x => asyncFunc(x))

// Wait for the functions to finish ?
(for (seqInt <- asyncs) yield seqInt).map {
    case results => // <-- problem here
        // Use the results 
}

我遇到的问题是结果属于Future[Seq[Int]]类型,但我预计它们会像第一个代码段中那样属于(Seq[Int], Seq[Int], Seq[Int])类型。

最后我想做的是启动动态数量的异步函数,它们都具有相同的Future返回类型,等待它们全部完成,然后一起使用它们的所有结果。

1 个答案:

答案 0 :(得分:1)

Future.sequence是我失踪的关键部分(感谢评论)

// Create a list of Futures
val asyncs: Seq[Future[Seq[Int]] = otherList.filter(x => someCondition).map(x => asyncFunc(x))

// Use Future.sequence to to execute them and return a list of sequence of integers
Future.sequence(asyncs).map{ 
    case results => // Use the results List[Seq[Int]]
}.recover {
    case error => // Oh no!
}