gpt4 book ai didi

scala - 在 Scala 中等待 "recursive" future

转载 作者:行者123 更新时间:2023-12-04 23:03:13 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com