|
| 1 | +/* |
| 2 | + * Copyright (C) 2012 Typesafe Inc. <http://www.typesafe.com> |
| 3 | + */ |
| 4 | + |
| 5 | +package scala.async |
| 6 | + |
| 7 | +import scala.language.experimental.macros |
| 8 | +import scala.concurrent.{Future, ExecutionContext} |
| 9 | +import scala.reflect.internal.annotations.compileTimeOnly |
| 10 | + |
| 11 | +/** |
| 12 | + * Async blocks provide a direct means to work with [[scala.concurrent.Future]]. |
| 13 | + * |
| 14 | + * For example, to use an API to that fetches as web page to fetch |
| 15 | + * two pages and add their lengths: |
| 16 | + * |
| 17 | + * {{{ |
| 18 | + * import ExecutionContext.Implicits.global |
| 19 | + * import scala.async.Async.{async, await} |
| 20 | + * |
| 21 | + * def fetchURL(url: URL): Future[String] = ... |
| 22 | + * |
| 23 | + * val sumLengths: Future[Int] = async { |
| 24 | + * val body1 = fetchURL("http://scala-lang.org") |
| 25 | + * val body2 = fetchURL("http://docs.scala-lang.org") |
| 26 | + * await(body1).length + await(body2).length |
| 27 | + * } |
| 28 | + * }}} |
| 29 | + * |
| 30 | + * Note that the in the following program, the second fetch does *not* start |
| 31 | + * until after the first. If you need to start tasks in parallel, you must do |
| 32 | + * so before `await`-ing a result. |
| 33 | + * |
| 34 | + * {{{ |
| 35 | + * val sumLengths: Future[Int] = async { |
| 36 | + * await(fetchURL("http://scala-lang.org")).length + await(fetchURL("http://docs.scala-lang.org")).length |
| 37 | + * } |
| 38 | + * }}} |
| 39 | + */ |
| 40 | +object Async { |
| 41 | + /** |
| 42 | + * Run the block of code `body` asynchronously. `body` may contain calls to `await` when the results of |
| 43 | + * a `Future` are needed; this is translated into non-blocking code. |
| 44 | + */ |
| 45 | + def async[T](body: T)(implicit execContext: ExecutionContext): Future[T] = macro internal.ScalaConcurrentAsync.asyncImpl[T] |
| 46 | + |
| 47 | + /** |
| 48 | + * Non-blocking await the on result of `awaitable`. This may only be used directly within an enclosing `await` block. |
| 49 | + * |
| 50 | + * Internally, this will register the remainder of the code in enclosing `async` block as a callback |
| 51 | + * in the `onComplete` handler of `awaitable`, and will *not* block a thread. |
| 52 | + */ |
| 53 | + @compileTimeOnly("`await` must be enclosed in an `async` block") |
| 54 | + def await[T](awaitable: Future[T]): T = ??? // No implementation here, as calls to this are translated to `onComplete` by the macro. |
| 55 | +} |
0 commit comments