映射未来在游戏控制器中不起作用

mapping future not working in play controller

我有一个播放控制器:

def createBlokPost() = Action { implicit request =>
    val postvals: Option[Map[String, Seq[String]]] = request.body.asFormUrlEncoded
    postvals.map { args =>
      val email = args("email").head
      val name = args("name").head
      val population = args("population").head
      val location = args("location").head
      val studentRequirements = args("Student Requirements").head
      val schoolFundingMethod = args("School funding method").head

      val createSchool = modelPersistent.createSchool(email, name, population.toShort, location, studentRequirements.toShort, schoolFundingMethod.toShort)

      var workedVal = false

      createSchool.map { thing =>
        thing match {
          case Some(i) => workedVal = true
          case None => workedVal = false
        }
      }

      if (workedVal) {
        Ok("It frickin worked!")
      } else {
        Ok("Something went wrong on our end :( \nYour school may already have a Blok.")
      }
    }.getOrElse(Ok("Oops. You're a loser. Something went wrong and we cannot help you because in reality... we dont care enough. \nImagine being such a loser that something went wrong on the sign up page .\n\nBTW. Every time this happens I get a notification telling me that someone fucked up and do you know what I do? I laugh knowing that there is some degenerate out there with the ability to fail so quickly."))
  }

createSchool 是一个未来[选项[Int]]。在我的测试项目中,这是有效的,所以我认为将它放入控制器是一个问题。我收到的错误是:

[error] a.a.ActorSystemImpl - Uncaught error from thread [application-akka.actor.default-dispatcher-10]
scala.runtime.NonLocalReturnControl: null

我不知道这是什么意思,但控制器仍在完成,这意味着该行已添加到数据库中并且它 returns“我们这边出了点问题:(\n你的学校可能已经有一个Blok。”。我也尝试过 flatMap 和 onComplete,但它们都不起作用。此外,我尝试使操作异步,但无法编译。

问题是它没有改变布尔值 workedVal,即使它正在工作,它也总是返回 false。

如有任何帮助,我们将不胜感激。

发生的事情基本上是:

  • createSchool(...)Future 结果绑定到 createSchool
  • workedVal初始化为false
  • 回调已附加到 createSchool
  • workedVal 被检查并且 false
  • Ok 返回错误信息
  • createSchoolFuture完成
  • 执行回调,可能设置workedVal

您必须将其设为异步 Action,这意味着每条路径都必须生成 Future

所以像这样的东西应该可以工作

postvals.map { args =>
  // the args lookups... they're a bit hinky, but setting that aside
  modelPersistent.createSchool(email, name, population.toShort, location, studentRequirements.toShort, schoolFundingMethod.toShort)
    .map { createResult =>
      if (createResult.isDefined) Ok("It frickin' worked!")
      else Ok("Something went wrong on our end :( \nYour school may already have a Blok.")
    }
}.getOrElse {
  Future.successful(Ok("Oops. You're a loser. Something went wrong and we cannot help you because in reality... we dont care enough. \nImagine being such a loser that something went wrong on the sign up page .\n\nBTW. Every time this happens I get a notification telling me that someone fucked up and do you know what I do? I laugh knowing that there is some degenerate out there with the ability to fail so quickly."))
}