簡體   English   中英

在游戲行動中嵌套期貨

[英]Nesting Futures in Play Action

我正在使用Play並采取行動,我想做兩件事: -

  1. 首先檢查我的緩存中的值
  2. 其次,使用該值調用Web服務

由於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)
        }

    }

}

我擔心的是,這可能不是最有效的做事方式,因為我假設不同的線程可以處理完成每個期貨的任務。

我們非常感謝任何有關更好方法的建議。

這不是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 (例如全局的,Play Play,......)。

WS.get返回Future ,它不應該在cacheFuture.map ,否則它將返回Future[Future[...]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM