scala - 在 Scala 中等待 "recursive" future

标签 scala future

描述我的问题的简单代码示例:

import scala.util._
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global

class LoserException(msg: String, dice: Int) extends Exception(msg) { def diceRoll: Int = dice }

def aPlayThatMayFail: Future[Int] = {
    Thread.sleep(1000) //throwing a dice takes some time...
    //throw a dice:
    (1 + Random.nextInt(6)) match {
        case 6 => Future.successful(6) //I win!
        case i: Int => Future.failed(new LoserException("I did not get 6...", i))
    }
}

def win(prefix: String): String = {
    val futureGameLog = aPlayThatMayFail
    futureGameLog.onComplete(t => t match {
        case Success(diceRoll) => "%s, and finally, I won! I rolled %d !!!".format(prefix, diceRoll)
        case Failure(e) => e match {
            case ex: LoserException => win("%s, and then i got %d".format(prefix, ex.diceRoll))
            case _: Throwable => "%s, and then somebody cheated!!!".format(prefix)
        }
    })
"I want to do something like futureGameLog.waitForRecursiveResult, using Await.result or something like that..."
}

win("I started playing the dice")   

这个简单的例子说明了我想要做什么。基本上,如果说的话,我想等待一些计算的结果,当我对以前的成功或失败的尝试组合不同的 Action 时。

那么您将如何实现 win方法?

我的“现实世界”问题,如果有什么不同的话,是使用 dispatch对于异步 http 调用,我想在前一个调用结束时继续进行 http 调用,但操作因前一个 http 调用是否成功而异。

最佳答案

您可以通过递归调用恢复失败的 future :

def foo(x: Int) = x match {
  case 10 => Future.successful(x)
  case _ => Future.failed[Int](new Exception)
}

def bar(x: Int): Future[Int] = {
  foo(x) recoverWith { case _ => bar(x+1) }
}

scala> bar(0)
res0: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@64d6601

scala> res0.value
res1: Option[scala.util.Try[Int]] = Some(Success(10))
recoverWith需要一个 PartialFunction[Throwable,scala.concurrent.Future[A]]并返回 Future[A] .不过你应该小心,因为当它在这里进行大量递归调用时会使用相当多的内存。

关于scala - 在 Scala 中等待 "recursive" future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17989973/

相关文章:

scala - 使用 sc.textFile() 加载本地文件以激发

scala - 如何使用 sbt 创建包含源(.java 和 .scala)和类的 .jar?

scala - 构建 play 2.0 项目时 Unresolved 依赖关系

scala - 何时使用 Scala Future?

multithreading - 如何使用Akka的 future 获得异步结果

scala - 没有单独线程的同步 Scala Future

Scala 替代我一直使用的 Java 枚举模式

java.lang.IndexOutOfBoundsException : No group 1 | Pattern matching

c++ - 在不同线程中执行 future 时避免破坏对象

java - Java 中有 ResolvedFuture 类吗?