joesan
joesan

Reputation: 15345

Play Action Async wrapping a Future

Let's say I have an Action Async block as below in one of my controller:

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

What would it mean to wrap Step 1 and Step 2 in a Future? Is the Action.async enough to make myCntr calls asynchronous?

Upvotes: 0

Views: 901

Answers (1)

dwickern
dwickern

Reputation: 3519

Action.async is not enough to make your code asynchronous. Here is the signature for async (I picked the simplest overload):

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

It's up to you to provide that Future. If you're calling blocking code you can execute it concurrently like Future { blockingCode() }. However the preferred way is to use futures throughout your application.

A simple action might look something like this:

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

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

Upvotes: 1

Related Questions