Both are blocking for at most the given Duration
. However, Await.result
tries to return the future result right away and throws an exception if the future failed while Await.ready
returns the completed future from which the result (Success
or Failure
) can safely be extracted via the value
property.
The latter is very handy when you have to deal with a timeout as well:
val future = Future { Thread.sleep(Random.nextInt(2000)); 123 }
Try(Await.ready(future, 1.second)) match {
case Success(f) => f.value.get match {
case Success(res) => // handle future success
case Failure(e) => // handle future failure
}
case Failure(_) => // handle timeout
}
When using Await.result
, the timeout exception and exceptions from failing futures are "mixed up".
Try(Await.result(future, 1.second)) match {
case Success(res) => // we can deal with the result directly
case Failure(e) => // but we might have to figure out if a timeout happened
}
Await.ready
will not return theTry
directly but you have to extract it from the future first viaAwait.ready(a, d).value.get
. – Buckling