我尝试编写动作来生成图片的拇指,并向用户显示它是否尚未生成。 问题是:生成部分在异步中运行,并在生成部分完成之前显示部分代码。 我是Scala和Play Framework的新手,无法让show等待。我试过这样的话:
def thumbs(profiletype: String, id: Int, filename: String, extention: String) = Action {
val content = File.getBinaryContent(pathToDir + filename + "." + extention)
content match {
case Some(c) => Ok(c).as(File.getContentType(extention))
case _ => val picture = Picture.getById(id)
picture match {
case None => NotFound("Page not found")
case Some(p) => val rslt = Future (p.generateThumbs(pathToDir, profiletype))
val r=rslt.map(a=>a)
Await.ready(r, Duration(8, "second"))
Logger.debug(pathToDir + filename + "." + extention)
val content = File.getBinaryContent(pathToDir + filename + "." + extention)
renderBinary(content, File.getContentType(extention))}
}
}
并且喜欢这样没有运气
def thumbs(profiletype: String, id: Int, filename: String, extention: String) = Action {
val content = File.getBinaryContent(pathToDir + filename + "." + extention)
content match {
case Some(c) => Ok(c).as(File.getContentType(extention))
case _ => val picture = Picture.getById(id)
picture match {
case None => NotFound("Page not found")
case Some(p) => val rslt = Future (p.generateThumbs(pathToDir, profiletype))
Await.ready(rslt, Duration(8, "second"))
Logger.debug(pathToDir + filename + "." + extention)
val content = File.getBinaryContent(pathToDir + filename + "." + extention)
renderBinary(content, File.getContentType(extention))}
}
}
此Await不起作用,并且在p.generateThumbs完成之前记录日志
答案 0 :(得分:4)
您可以return a Future[Result]
使用Await.ready
或Await.result
,而不是在等待生成缩位条之前异步生成缩略图并阻塞({3}}或Option
)。
在你的情况下,这看起来像(未经测试):
(我还将您的map
模式匹配转换为getOrElse
和def thumbs(
profiletype: String, id: Int, filename: String, extention: String
) = Action.async { // return an (explicit) asynchronous result
val filepath = pathToDir + filename + "." + extention
File.getBinaryContent(filepath)
.map ( content =>
// we found the thumbnail, return its content as a Future[Result]
Future.successful(Ok(content).as(File.getContentType(extention)))
)
.getOrElse {
// we have not found the thumbnail, check if the Picture exists
Picture.getById(id)
.map { picture =>
// we found the Picture, lets generate the thumbnails
Future(picture.generateThumbs(pathToDir, profiletype))
.map { futureResult =>
// the thumbnails are created
// return the content of the thumbnail
// and since we are in a Future.map this will be a Future[Result]
Logger.debug(filepath)
val content = File.getBinaryContent(filepath)
renderBinary(content, File.getContentType(extention))
}
}
// we could not find the Picture return a NotFound as Future[Result]
.getOrElse(Future.successful(NotFound("Page not found")))
}
}
函数。)
println("Tag of button: \(button.tag)")
这样我们只有一个阻塞线程,创建缩略图而不是两个,一个创建缩略图,一个等到第一个线程完成创建缩略图。
播放可以在创建缩略图时提供其他请求,创建缩略图后播放将使用缩略图进行响应。