3
考慮以下兩種方法:處理失敗的`Future`
def f: Future[Int] = Future { 10 }
def g: Future[Int] = Future { 5 }
我想撰寫他們:
scala> import scala.concurrent.Future
import scala.concurrent.Future
scala> import scala.concurrent.Future._
import scala.concurrent.Future._
scala> import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.ExecutionContext.Implicits.global
scala> for {
| a <- f
| b <- g
| } yield (a+b)
res2: scala.concurrent.Future[Int] = [email protected]
現在,我會打電話給Await.result
阻塞,直到它完成。
scala> import scala.concurrent.duration._
import scala.concurrent.duration._
正如預期的那樣,我得到15
,因爲Await.result
拿了Future[Int]
和返回Int
。
scala> Await.result(res2, 5.seconds)
res6: Int = 15
定義爲recoverFn
一個失敗的未來:
scala> val recoverFn: PartialFunction[Throwable, Future[Int]] =
{ case _ => Future{0} }
recoverFn: PartialFunction[Throwable,scala.concurrent.Future[Int]] = <function1>
我試圖定義一個failedFuture:
scala> def failedFuture: Future[Int] = Future { 666 }.failed.recoverWith{ recoverFn }
<console>:20: error: type mismatch;
found : scala.concurrent.Future[Any]
required: scala.concurrent.Future[Int]
def failedFuture: Future[Int] = Future { 666 }.failed.recoverWith{ recoverFn }
^
但是,我得到上面的編譯時錯誤。
具體來說,我該如何解決這個錯誤?一般來說,Future#recoverWith
通常如何處理Future
的處理失敗?