2016-02-25 70 views
1

进出口使用播放和拥有,我想要做的两件事情的操作: -嵌套期货在玩动作

  1. 首先检查我的缓存值
  2. 其次,调用与价值的网络服务

由于WS API返回Future,我使用的是Action.async
我的Redis缓存模块还返回Future

假设我对可能长时间运行的任务适当地使用了另一个ExecutionContext。

问:有人可以通过以下步骤确认我是否在正确的轨道上。我知道我没有满足以下例外情况 - 只是为了简洁而保持简单。

def token = Action.async { implicit request => 


    // 1. Get Future for read on cache 

    val cacheFuture = scala.concurrent.Future { 
     cache.get[String](id)  
    } 


    // 2. Map inside cache Future to call web service 

    cacheFuture.map { result => 

     WS.url(url).withQueryString("id" -> result).get().map { response => 
      // process response 
      Ok(responseData) 
     } 

    } 

} 

我担心的是,这可能不是做事情的最有效的方式,因为我认为不同的线程可以处理完成每一个期货的任务。

任何建议更好的方法,不胜感激。

回答

3

这不是特定于Play的。我建议你看一下文档解释Future的工作原理。

val x: Future[FutureOp2ResType] = futureOp1(???).flatMap { res1 => futureOp2(res1, ???) } 

或者与-理解

val x: Future[TypeOfRes] = for { 
    res1 <- futureOp1(???) 
    res2 <- futureOp2(res1, ???) 
    // ... 
} yield res 

对于Future s的执行方式(使用线程),这取决于其ExecutionContext使用(例如全球性的游戏之一。 ..)。

WS.get返回Future,它不应该被内cacheFuture.map叫,否则会返回一个Future[Future[...]]

+0

好cchantep感谢您的意见。如果能够帮助解决我的问题,我会在文档中进一步挖掘并回来。 – JamieP