In Scala, the resulting value of a future is wrapped in either a Success
or Failure
type, which is a type of Try
. Hence, the value in a Future is always an instance of one of the Try
types: Success
or Failure
.
Since these are Try
types, you can register a callback on a future which accepts a Try
type. An example is to use the onComplete
which takes a callback function of type Try[T] => U
and returns a Unit
.
import scala.util.{Success, Failure}
val f: Future[List[String]] = Future {
session.getUserNamesFromDatabase
}
f onComplete {
case Success(users) => for (user <- users) println(user)
case Failure(t) => println("An error has occurred: " + t.getMessage)
}
The benefit of a callback on a future is that it can complete without blocking the client. So the callback can execute completely asynchronously.
Note: that the onComplete
method has a unit
return type. So it cannot be chained.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…