斯卡拉期货回调地狱

Krz*_*nde 7 scala future callback

我一直在读Scala Futures多次减少回调问题.我有一个代码开始看起来有问题.

val a = Future(Option(Future(Option(10))))

a.map { b =>
  b.map { c =>
    c.map { d =>
      d.map { res =>
        res + 10
      }
    }
  }
} 
Run Code Online (Sandbox Code Playgroud)

如何让这段代码更平坦?

//编辑@againstmethod

for{
  b <- a
  c <- b
  d <- c
  res <- d
} yield res + 10
Run Code Online (Sandbox Code Playgroud)

此代码将无法编译

错误:(21,8)类型不匹配; 找到:需要选项[Int]:
scala.concurrent.Future [?] res < - d
^

Krz*_*nde 1

事实上,答案很简单。

for { 
a <- b
c <- a.get
} yield c.get + 10
Run Code Online (Sandbox Code Playgroud)

似乎就足够了,因为当x.get + 10失败(因为None + 10)时,未来就会失败。所以使用简单的后备仍然有效

val f = for { 
a <- b
c <- a.get
} yield c.get + 10
f fallbackTo Future.successful(0)
Run Code Online (Sandbox Code Playgroud)