响应异步结果的模式

Pattern for responding with async result

我正在尝试使以下示例正常工作:

def asyncTest = Action {

    val willBeInt = Future {
        Thread.sleep(5000)
        100
    }

    willBeInt.onComplete({
        case Success(value) => Ok(s"Value = $value")
        case Failure(e) => Failure(e)
    })
}

但是我收到有关重载方法的错误消息:

Overloaded method value [apply] cannot be applied to  (Unit)

我有 NodeJS 背景,正在努力弄清楚这些回调应该如何工作,同时返回结果以安抚方法签名。

Action 视为一个 return 承诺的函数,而不是一个接受回调的函数。在 Scala 术语中,您将 returning Future。 Play 的内部将自行调用 onComplete(或类似的东西)(类似于 javascript Promise 的 then 函数)。

具体来说,您的编译错误是由于 onComplete returns Unit,而 Action 块期望您 return一个Future。您可以使用 map 将您的 willBeInt 未来转变为 Play 所期待的:

def asynTest = Action.async {
  val willBeInt = Future {
    Thread.sleep(5000)
    100
  }

  // note you will probably need to
  // import scala.concurrent.ExecutionContext.Implicits.global
  // to be able to call `map` here
  willBeInt map { value =>
    Ok(s"Value = $value")
  } recover {
    case e: Throwable => InternalServerError(e.toString)
  }
}

如需额外阅读,请查看 the docs for Future, and the docs for Action