1 问题背景
我们先看一下Play中Action代码的基本结构:
1def greeting = Action.async { implicit request => 2 for{ 3 r1 <- Future.successful("result") 4 r2 <- Future.successful("result") 5 } yield { 6 Ok("hello") 7 } 8}
Action的body部分返回类型是Future[Result]。如果只是简单的数据库查询操作,使用for表达式就足够了,就像上面那样。但是如果在yield部分还需要做一些异步的业务处理,问题就出现了,例如下面这个保存商品信息的Action代码:
1def doEditProduct(_id: String) = Action.async { implicit request => 2 for{ 3 product <- fetchProductAsync 4 other <- otherInfoAsync 5 } yield { 6 //比较一下,看看哪些信息在页面上被修改了 7 //... 8 updateProductAsync() 9 Redirect(routes.ProductController.editProduct(_id)) 10 } 11}
首先利用for语句取出异步的product结果,然后对比一下页面数据和数据库中的差异,这一步在很多时候是需要的,例如记录修改日志,然后异步更新至数据库,接着将页面跳转至该商品的编辑页面。那么问题来了,跳转至编辑页面后用户看到的是编辑前的结果还是编辑后的结果?呵呵,只能看运气了!很可能在更新操作未完成之前,编辑页面已经刷出来了。面对这种情况,你很可能会说同步等待updateProductAsync()的结果返回呗,千万别这么干,高并发时你的线程很快就耗尽了,另外updateProductAsync()操作之后可能还会有其它的异步更新操作,就像这样:
1def doEditProduct(_id: String) = Action.async { implicit request => 2 for{ 3 product <- fetchProductAsync 4 other <- otherInfoAsync 5 } yield { 6 //比较一下,看看哪些信息在页面上被修改了 7 //... 8 updateProductAsync().map{ writeResult => 9 if(...){ asyncOperate1() } else { asyncOperate2() } 10 } 11 Redirect(routes.ProductController.editProduct(_id)) 12 } 13}
如果asyncOperate1() 和asyncOperate2()也会更新商品信息, 你可能就要骂娘了...
2 解决方案
其实上面的问题可以归结为本文的标题,即如何从多层Future中取出最终的执行结果。其实for语句可以很容易解决这个问题:
1def doEditProduct(_id: String) = Action.async { implicit request => 2 val multiLevelsFuture = 3 for{ 4 product <- fetchProductAsync 5 other <- otherInfoAsync 6 } yield { 7 updateProductAsync().map{ writeResult => 8 asyncOperate1.map{ writeResult1 => 9 Redirect(routes.ProductController.editProduct(_id)) 10 } 11 } 12 } 13 14 for{ 15 level1Future <- multiLevelsFuture 16 level2Future <- level1Future 17 finalResult <- level2Future 18 } yield { 19 finalResult 20 } 21}
for语句最终会被编译器翻译为map和flatMap,我们索性直接上,而且代码更简洁:
1def doEditProduct(_id: String) = Action.async { implicit request => 2 (for{ 3 product <- fetchProductAsync 4 other <- otherInfoAsync 5 } yield { 6 updateProductAsync().map{ writeResult => 7 asyncOperate1.map{ writeResult1 => 8 Redirect(routes.ProductController.editProduct(_id)) 9 } 10 } 11 }).flatMap(f1 => f1.flatMap(f2 => f2)) 12}
注意,for ... yield需要用一对圆括号括起来。转载请注明作者: joymufeng