Play Action 异步包装 Future

Play Action Async wrapping a Future

假设我的一个控制器中有如下所示的 Action Async 块:

def myCntr = Action.async { implicit request =>
  // Step 1. .... // look up over the network
  // Step 2. .... // do a database call
}

将步骤 1 和步骤 2 包装在 Future 中意味着什么? Action.async 是否足以使 myCntr 调用异步?

Action.async 不足以使您的代码异步。这是 async 的签名(我选择了最简单的重载):

def async(block: => Future[Result]): Action[AnyContent]

由你来提供那个 Future。如果您正在调用阻塞代码,您可以像 Future { blockingCode() } 一样并发执行它。但是,首选方法是在整个应用程序中使用期货。

一个简单的动作可能看起来像这样:

  def lookup(): Future[Connection] = ???
  def query(c: Connection): Future[QueryResult] = ???

  def myCntr = Action.async {
    for {
      conn <- lookup()
      result <- query(conn)
    } yield NoContent
  }