I noticed that methods ready
and result
of scala.concurrent.Future
cannot be invoked directly. When I call them in REPL I get an error. Thus I have to call Await.ready
and Await.result
instead.
It is Ok but looks a bit awkward. So now I wonder:
The onComplete method is general in the sense that it allows the client to handle the result of both failed and successful future computations. In the case where only successful results need to be handled, the foreach callback can be used: Scala 2. Scala 3.
Future represents a result of an asynchronous computation that may or may not be available yet. When we create a new Future, Scala spawns a new thread and executes its code. Once the execution is finished, the result of the computation (value or exception) will be assigned to the Future.
The Promise is a writable, single-assignment container that completes a Future. The Promise is similar to the Future. However, the Future is about the read-side of an asynchronous operation, while the Promise is about the write-side.
Await. result tries to return the Future result as soon as possible and throws an exception if the Future fails with an exception while Await. ready returns the completed Future from which the result (Success or Failure) can safely be extracted.
The reasons are laid out in official doc:
The Future trait implements the Awaitable trait with methods method ready() and result(). These methods cannot be called directly by the clients– they can only be called by the execution context.
That way library designers enforce you to use those methods in proper environment (execution context, perhaps third party, or via Awaitable object to denote blocking operations explicitly).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With