我希望像下面这样的代码能够等待两个未来事件,但实际上它并不能。
object Fiddle {
val f1 = Future {
throw new Throwable("baaa") // emulating a future that bumped into an exception
}
val f2 = Future {
Thread.sleep(3000L) // emulating a future that takes a bit longer to complete
2
}
val lf = List(f1, f2) // in the general case, this would be a dynamically sized list
val seq = Future.sequence(lf)
seq.onComplete {
_ => lf.foreach(f => println(f.isCompleted))
}
}
val a = FuturesSequence
我曾认为seq.onComplete
会等待所有操作完成后再自行结束,但实际上它的结果是:
true
false
.sequence
在 scala.concurrent.Future 的源代码中有些难以理解,我想知道如何实现一个等待动态大小的序列中所有原始future完成的并行操作,或者这里可能存在什么问题。编辑:一个相关的问题:https://worldbuilding.stackexchange.com/questions/12348/how-do-you-prove-youre-from-the-future :)
Try
本质上是将执行结果的输出值或流程控制异常映射到成功或失败的返回值? - matansterTry
。在需要扩展 Future 特质(使用隐式类进行 pimping)的地方,我已经开始使用 Promise 了。 - matansterTry
本质上是一个同步的Future
,其中你只有两种状态(成功和失败),而不是三种状态(未满足、成功、失败),这正好适用于这个问题。 - Travis Brown