簡體   English   中英

使用不僅僅包含期貨的for循環鏈接期貨

[英]chaining futures with for loop containing not only futures

將2個期貨鏈接在一起時,我遇到以下問題:

import scala.concurrent.{ ExecutionContext, Future } 

 def lastFiveFullNews: Future[Seq[FullNews]] = {
  for (
  seq <- getLastFiveNews;
  news <- seq;
  fullNews <- getFullNewsById(news.id) //error at this line

) yield fullNews
}

具有以下方法簽名:

def getLastFiveNews: Future[Seq[News]]
def getFullNewsById(id: Long): Future[FullNews]
def lastFiveFullNews: Future[Seq[FullNews]]

基本上,會生成具有新聞ID的FullNews。 在Idea編輯器中,未報告任何錯誤,但播放編譯器顯示:

類型不匹配; 找到:scala.concurrent.Future [FullNews]必需:scala.collection.GenTraversableOnce [?]

我認為這是行不通的,因為在for循環中不僅有scala的Futures,而且還有Seq。 但是沒有Seq,我不知道如何編寫。 有任何想法嗎 ? 謝謝。

如您所懷疑,您不能在理解中混用不同的單子。 由於您正在使用Future ,因此具有理解力的所有行都必須產生Future 您可以使用Future.sequence ,它將Seq[Future[...]]轉換為Future[Seq[...]]

def lastFiveFullNews: Future[Seq[FullNews]] = {
  for (
    seq <- getLastFiveNews
    fullNews <- Future.sequence(
      seq.map(news => getFullNewsById(news.id))
    )
  ) yield fullNews
}

暫無
暫無

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

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