Scala将未来值保存到变量

时间:2016-03-17 16:31:59

标签: scala codeigniter

我插入人的功能:

def InsertPerson = Action(BodyParsers.parse.json) { request =>
val b = request.body.validate[Person]
b.fold(
  //errorForm => Future.successful(Ok(views.html.index(errorForm, Seq.empty[User]))),
  errors => {
    BadRequest(Json.obj("status" -> "error", "message" -> JsError.toJson(errors)))
  },
  person => {
    val f = ApplTagService.insertPerson(person)
      f.map(res => "User successfully added").recover {
        case ex: Error => ex.getMessage
      }
      f onFailure {
        case t => println("An error has occured: " + t.getMessage)
    }

    Ok(Json.obj("status" -> f.toString() ))

  })}

我将Json从CI发送到scala以获取插入人员,然后我想发出警告,如果该插入成功与否,我需要在变量上保存ex.getMessaget.getMessage并发送它到CI

我现在在CI中的f.toString()获得的内容是scala.concurrent.impl.Promise$DefaultPromise@793e6657

如何在CI中显示ex.getMessaget.getMessage

1 个答案:

答案 0 :(得分:0)

如果您想要返回Action.async(BodyParsers.parse.json)而不是Action(BodyParsers.parse.json)

,则可以使用Future[Result]代替Result

在这种情况下,您的匹配将如下所示

b.fold(
  errors => Future.successful(BadRequest(Json.obj("status" -> "error", "message" -> JsError.toJson(errors)))),
  person => {
    val f = ApplTagService.insertPerson(person)
    val fMessage = f.map(res => "User successfully added").recover {
      case ex: Error => ex.getMessage
    }
    f onFailure {
      case t => println("An error has occured: " + t.getMessage)
    }

    fMessage.map(message => Ok(Json.obj("status" -> message )))
})