在 Play Action 中嵌套期货

Nesting Futures in Play Action

我正在使用 Play 并有一个动作我想做两件事:-

  1. 首先检查我的缓存是否有值
  2. 其次,使用值
  3. 调用网络服务

因为 WS API returns a Future, 我正在使用 Action.async.
我的Redis缓存模块也是returns一个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)
        }

    }

}

我担心这可能不是最有效的做事方式,因为我假设不同的线程可能会处理完成每个 Futures 的任务。

非常感谢任何关于更好方法的建议。

这不是 Play 特有的。我建议您查看解释 Future 工作原理的文档。

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

或加理解

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

至于 Future 的执行方式(使用线程),这取决于您使用的 ExecutionContext(例如全局的,播放的,...)。

WS.get returning a Future, it should not be called within cacheFuture.map, or it will returns a Future[Future[...]].