スカラ先物: With Await.resultプログラムを終了する前に、未来が完了するのを待つことができます。、Future.onFailureが完了するのを待つ方法は?
プログラムを終了する前にFuture.onFailureが完了するのを待つ方法はありますか?
package test
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
object Test5 extends App {
def step(i: Int): Future[String] = Future {
Thread.sleep(1000)
if (i == 3) throw new Exception("exception on t3")
Thread.sleep(1000); val s = s"done: $i"; println(s); s
}
val task: Future[String] = step(1).flatMap(_ => step(2).flatMap(_ => step(3)))
task.onFailure {
case e: Throwable => println("task.onFailure. START: " + e); Thread.sleep(3000); println("task.onFailure. END.")
}
try {
val result: String = Await.result(task, Duration.Inf)
println("RESULT: " + result)
} catch {
case e: Throwable => println("Await.result.try catch: " + e)
}
// without this, "task.onFailure. END." does not get printed.
// How can I replace this line with something such as Await.result([the task.onFailure I set previously])
Thread.sleep(5000)
println("END")
}
注:代わりにtask.onFailure
を使用しての、私は(例のように)Await.result
上の例外をキャッチすることができます。しかし、task.onFailure
を使用することをお勧めします。
更新 溶液をライアンによって提案されているようtransform
又はrecover
を使用することです。私の場合、何かが必要でしたが、私はこの代替の答えを追加しました:on scala, how to wait for a Future.onFailure to complete?
はい、それはもっと簡単です。ありがとう。 –