2016-03-18 53 views
1

我有以下代码:动态创建期货的理解和等待完成

// 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返回类型的动态量,等待他们全部结束,然后利用其所有的结果一起。

+6

'Future.sequence(异步操作)'关键部分 – cchantep

回答

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! 
}