【发布时间】:2018-10-24 23:22:22
【问题描述】:
我的播放框架 API 服务器有问题。我需要在后台运行一些处理,返回带有结果的Future,然后将结果写入响应。但是,请求线程在我的 Future 完成之前全力以赴并返回。这是代码...
def requestAction(): Action[AnyContent] = Action.async { implicit request =>
var fResult: Future[String] = Future { "initial value" }
try {
fResult = doSomethingAsyncAndGetResponseString(); // return "great, everything is done"
}
catch {
case t: Throwable {
fResult = Future { "failed" }
}
}
// done, return response, but the problem is, this is executed first because doSomethingAsyncAndGetResponseString() is still executing and returns later
fResult.map( res => {
// problem here, because I get "initial value" which is not what I want
Ok(res)
}
}
没有Async.await,有没有办法让“很棒,一切都完成”或“失败”?我一直在我的 API 服务器中使用这种格式,但今天它坏了,因为在我编写的一个新 API 中,doSomethingAsyncAndGetResponseString 有点长。我没想到,所以我对结构的理解一定有问题。
提前致谢!
【问题讨论】:
标签: scala playframework future