动态创建以理解 Futures 并等待完成
Dynamically create for comprehension of Futures and wait for completion
我有以下代码:
// 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
return 类型,等待它们全部完成,然后使用它们的所有结果一起。
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!
}
我有以下代码:
// 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
return 类型,等待它们全部完成,然后使用它们的所有结果一起。
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!
}