0
votes

I am trying to complete a Promise[String] for my Action. So far I've read the Play's documentation on asynchronous programming at http://www.playframework.com/documentation/2.0/ScalaAsync but there's something I am not getting - or the docs are wrong :)

Here's an outline of my code. My intention is to return a Promise[String] and complete that in my Action. The content of the Promise may come from different places, so I would like to be able to return a Promise[String] to have the Action handler simple.

def getJson = Action { request =>
  val promiseOfJson = models.item.getJson
  Async {
    promiseOfJson.map(json => Ok(json))
  }   
}

def models.item.getJson: Promise[String] = {
  val resultPromise = promise[String]
  future {
     ...
     resultPromise success "Foo"
  }

  resultPromise
}

Looking at Play's documentation and at "AsyncResult" I think I am doing the same thing, no?

Problem is that I get a compilation error inside my Async {} block:

value map is not a member of scala.concurrent.Promise[String]

1

1 Answers

1
votes

Turns out that Play fundamentally changed how Asyncs work between Play versions 2.0 and 2.1.

By Googling "Play Async" you first get the docs for version 2.0, which is why my above code won't work. This is the outdated version of the docs!

In Play 2.1 (docs are here: http://www.playframework.com/documentation/2.1.0/ScalaAsync) the Async completes a Future[T] instead of Promise[T]. In Play 2.0 Async completes a Promise[T], which is what I had (but I am running Play 2.1).

I changed my code to this and it works as expected:

def models.item.getJson: Future[String] = {
  val resultPromise = promise[String]
  future {
     ...
     resultPromise success "Foo"
  }

  resultPromise.future
}