Play Scala Converting sync to async

182 Views Asked by At

I've been trying to run an Action combined with Action async. I want to know how to run a separate async thread to retrieve some data from the server, and do a redirect or badrequest based off of that result asynchronously. Right now I have to send out a status code on the main thread, but the async thread does not do anything. I do not know why.

Heres the code :

def submitAuth = Action { implicit request =>
    loginForm.bindFromRequest.fold(
    errors => BadRequest(views.html.home.index(errors)),
    {
      case (loginUser) =>
        val result = Action.async {
          for {
            userCheck <- getUser(loginUser.email, loginUser.password)
          } yield {
            if(userCheck){
              Redirect(routes.jobs.index()).addingToSession("email" -> loginUser.email)
            } else {
              BadRequest(views.html.home.index(loginForm.bindFromRequest.withGlobalError(Messages("error.login", email))))
            }
          }
        }
    })
    Ok ("'")
  }

Please help :)

1

There are 1 best solutions below

0
On BEST ANSWER

It's typically easier to wrap the entire action in an async method using Action.async. Then for any return results that aren't truly async you can wrap them in a Future.successful call (like your error result). Otherwise, mapping over the async calls and returning a result works well. See below (assumes getUser call returns a Future[Boolean]):

def submitAuth = Action.async { implicit request =>
  loginForm.bindFromRequest.fold(
  errors => Future.successful(BadRequest(views.html.home.index(errors))),
  {
    case (loginUser) =>
      getUser(loginUser.email, loginUser.password) map { userCheck =>
        if(userCheck){
          Redirect(routes.jobs.index()).addingToSession("email" -> loginUser.email)
        } else {
          BadRequest(views.html.home.index(loginForm.bindFromRequest.withGlobalError(Messages("error.login", email))))
        }
      }
    }
  )
}