在Scala中顺序组合任意数量的期货 [英] Sequentially combine arbitrary number of futures in Scala

查看:134
本文介绍了在Scala中顺序组合任意数量的期货的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是scala的新手,我尝试在scala 2.10RC3中结合多个Futures。 Futures 应按顺序执行。在文档 Scala SIP14 中,方法 andThen 定义为以顺序执行期货。我使用这种方法组合几个 Futures (见下面的例子)。我的期望是,它打印 6 但实际上的结果是 0 。我在这里做错了什么?我有两个问题:

I'm new to scala and I try to combine several Futures in scala 2.10RC3. The Futures should be executed in sequential order. In the document Scala SIP14 the method andThen is defined in order to execute Futures in sequential order. I used this method to combine several Futures (see example below). My expectation was that it prints 6 but actually the result is 0. What am I doing wrong here? I have two questions:

首先,为什么结果 0 。第二,如何结合几个 Futures ,使第二个 Future 的执行不会在第一个未来已完成。

First, why is the result 0. Second, how can I combine several Futures, so that the execution of the second Future does not start before the first Future has been finished.

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


推荐答案

andThen 用于副作用。

使用地图:

scala> List(1, 2, 3).foldLeft(Future { 0 }) {
     |  case (future, i) => future map { _ + i }
     | } onSuccess { case x => println(x) }
6

这篇关于在Scala中顺序组合任意数量的期货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆