简体   繁体   中英

chaining futures with for loop containing not only futures

I have a problem with chaining 2 futures together what I would like to do is the following :

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
}

with the following method signatures :

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

basically a FullNews is generated with a News' id. In the Idea editor no error is reported but the play compiler says :

type mismatch; found : scala.concurrent.Future[FullNews] required: scala.collection.GenTraversableOnce[?]

I think this doesn't work because in the for loop there is not only scala's Futures but also a Seq. But without the Seq I dont know how to write it. Any ideas ? Thanks.

As you suspect, you can't mix different monads in a for-comprehension. Since you're working with Future s, all the lines in the for-comprehension must produce Future s. You can use Future.sequence , which will convert a Seq[Future[...]] to a Future[Seq[...]] :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM