Scala-如何编写嵌套的理解而不在Scala中返回Future of Future?

时间:2018-11-29 08:10:52

标签: scala

我正在尝试执行以下操作:

NATURALLEFTOUTERJOIN(<table1>, <table2>)

问题出在我最内心的for { item <- createAnItem //createAnItem returns Future[Item] for (alphabet <- listOfAlphapbets) { for { a <- enterAlphabetsWithItem(alphabet.id, item.id) // enterAlphabetsWithItem returns a Future[NewAlphabets] } yield a } } yield item 理解之内,这是我所不希望的。有没有一种方法可以重构它,使得我不会获得期货的未来,但能够对列表中的每个字母执行最里面的for

1 个答案:

答案 0 :(得分:0)

考虑createItem返回Future [Item]

考虑listOfAlphabets返回List [String]

enterAlphabetsWithItem返回Future [String]

那么简单的解决方案就是

Future[String] resultFuture = createItem(input).flatMap(item => Future.sequence(listOfAlphabets.map(alphabet => enterAlphabetsWithItem(item, alphabet))))

Future.sequenceList[Future[X]]转换为Future[List[X]]