[英]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 : 将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
}
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. 基本上,会生成具有新闻ID的FullNews。 In the Idea editor no error is reported but the play compiler says :
在Idea编辑器中,未报告任何错误,但播放编译器显示:
type mismatch;
类型不匹配; found : scala.concurrent.Future[FullNews] required: scala.collection.GenTraversableOnce[?]
找到:scala.concurrent.Future [FullNews]必需: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. 我认为这是行不通的,因为在for循环中不仅有scala的Futures,而且还有Seq。 But without the Seq I dont know how to write it.
但是没有Seq,我不知道如何编写。 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. 由于您正在使用
Future
,因此具有理解力的所有行都必须产生Future
。 You can use Future.sequence
, which will convert a Seq[Future[...]]
to a Future[Seq[...]]
: 您可以使用
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.