描述我的問題,一個簡單的代碼示例:等待「遞歸」期貨階
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")
這個簡單的例子說明了什麼我想做的事情。基本上,如果用文字說話,我想等待一些計算的結果,當我在先前的成功或不成功的attampts上撰寫不同的動作時。如何使用win
方法?
我的「真實世界」的問題,如果這有什麼差別,使用dispatch
異步HTTP調用,在這裏我想保留,只要前一個結束使HTTP調用,但操作不同,在羯羊以前的HTTP調用成功或不。
你應該換你整個'aPlayThatMayFail'在未來'{...}'調用,而不是調用'Thread.sleep',然後一段時間後立即返回可用'未來' - 否則未來計算的阻塞部分將不會在未來運行,並將阻止調用者,就像任何非期貨代碼一樣。 –
正確:)無論如何,它只是爲了說明這個想法... –
是啊,我懷疑,但只是在以防萬一:) –