Async blocks provide a direct means to work with scala.concurrent.Future.
Async blocks provide a direct means to work with scala.concurrent.Future.
For example, to use an API that fetches a web page to fetch
two pages and add their lengths:
import ExecutionContext.Implicits.global
import scala.async.Async.{async, await}
def fetchURL(url: URL): Future[String] = ...
val sumLengths: Future[Int] = async {
val body1 = fetchURL("http://scala-lang.org")
val body2 = fetchURL("http://docs.scala-lang.org")
await(body1).length + await(body2).length
}
Note that in the following program, the second fetch does *not* start
until after the first. If you need to start tasks in parallel, you must do
so before await-ing a result.
val sumLengths: Future[Int] = async {
await(fetchURL("http://scala-lang.org")).length + await(fetchURL("http://docs.scala-lang.org")).length
}
Async blocks provide a direct means to work with scala.concurrent.Future.
For example, to use an API that fetches a web page to fetch two pages and add their lengths:
Note that in the following program, the second fetch does *not* start until after the first. If you need to start tasks in parallel, you must do so before
await
-ing a result.