鉴于以下方法返回Future
...
def getProducts: Future[List[Product]] = { ... }
def sendOrder(p: Product, n: Int): Future[Order] = { ... }
...我需要为sendOrder
返回的每件商品调用getProducts
,最后yield
处理的产品数量:
for {
products <- getProducts
// how do I iterate thru products and invoke sendOrder for each element?
...
} yield products.length
如何处理上述理解中的产品清单?
修改
事情变得更加复杂,因为我需要在sendOrder
之前调用第三个方法,当且仅当getProducts
实际返回一个非空列表时:
def doSomethingBeforeSendingOrder: Future[String] = { ... }
for {
p <- getProducts
// how do I invoke doSomethingBeforeSendingOrder before sendOrder and
// only if getProducts actually returns a nonEmptylist?
o <- Future.sequence(p.map(senderOrder(_,IDontKnowWhatThisIntMeans)))
} yield o.length
答案 0 :(得分:3)
我不会&#39;知道sendOrder的第二个arg应该来自哪里,但基本上你想做的事情如下:
for {
p <- getProducts
if p.nonEmpty
_ <- someOtherMethodThatReturnsAFuture
o <- Future.sequence(p.map(senderOrder(_,IDontKnowWhatThisIntMeans)))
} yield o.length
Future.sequence会将你的List [Future [Order]]变成未来[List [Order]]