【发布时间】:2019-05-21 04:25:25
【问题描述】:
我有两个 Future 函数:
def parseIntFuture(str: String) = Future{scala.util.Try(str.toInt).toOption}
def divideFuture(a: Int, b: Int) = Future{ if (b == 0) None else Some(a / b)}
现在我想连接它们并最终得到Future[Option[Int]] 类型的结果,这是第二个返回值,但如果我这样做:
def stringDivideBy(aStr: String, bStr: String) = {
val x = for {
aNum <- parseIntFuture(aStr)
bNum <- parseIntFuture(bStr)
} yield (aNum, bNum)
x.map(n => {
for{
a <- n._1
b <- n._2
} yield divideFuture(a, b)
})
}
实际上我会得到Future[Option[Future[Option[Int]]]] 而不是Future[Option[Int]]。我知道这是因为我将一个 Future 传递给另一个,但我不知道将这两个 Future 一个一个连接起来的正确方法是什么,避免使用 Await。我停止显式使用 Await,那么解决方案是什么?
【问题讨论】: