Chr*_*sse 10 concurrency scala future
我是scala的新手,我尝试在scala 2.10RC3中组合几个Futures.本Futures应该按顺序执行.在文档Scala SIP14中,andThen定义方法以便按顺序执行Futures.我用这种方法组合了几种Futures(见下面的例子).我的期望是它打印6但实际上结果是0.我在这做错了什么?我有两个问题:
首先,结果为什么0.其次,我如何组合几个Futures,以便第二个的执行Future在第一个Future完成之前不会开始.
val intList = List(1, 2, 3)
val sumOfIntFuture = intList.foldLeft(Future { 0 }) {
case (future, i) => future andThen {
case Success(result) => result + i
case Failure(e) => println(e)
}
}
sumOfIntFuture onSuccess { case x => println(x) }
Run Code Online (Sandbox Code Playgroud)
sen*_*nia 12
andThen用于副作用.它允许您指定在将来完成之后以及在用于其他之前要执行的某些操作.
使用地图:
scala> List(1, 2, 3).foldLeft(Future { 0 }) {
| case (future, i) => future map { _ + i }
| } onSuccess { case x => println(x) }
6
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4032 次 |
| 最近记录: |