斯卡拉期货回调地狱

时间:2015-02-05 12:24:08

标签: scala callback future

我一直在阅读Scala Futures多次减少回调问题。我的代码开始变得有问题了。

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

a.map { b =>
  b.map { c =>
    c.map { d =>
      d.map { res =>
        res + 10
      }
    }
  }
} 

如何让这段代码更平坦?

//编辑@againstmethod

for{
  b <- a
  c <- b
  d <- c
  res <- d
} yield res + 10

此代码无法编译

  

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

3 个答案:

答案 0 :(得分:2)

您可以使用for comprehension。例如:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

object Stuff extends App {
  val result = for {
    f1 <- Future { 10 + 1 }
    f2 <- Future { f1 + 2 }
  } yield f2
  result.onComplete(println)
}

结果将是13。

任何实现正确的mapflatMap函数的类都可以在for中以这种方式使用。

如果您不介意另一个依赖项,您也可以使用像scalaz这样的库并明确使用monadic绑定来解决问题(EDIT编码了一些Option类型来解决下面的注释):

import scalaz._
import Scalaz._
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.util.{Success,Failure}

object BindEx extends App {

  def f1(i: String): Future[Int] = Future { i.length }
  def f2(i: Int): Future[Option[Double]] = Future { Some(i / Math.PI) }
  def f3(i: Option[Double]): Future[Option[Double]] = Future { 
    i match {
      case Some(v) => Some(Math.round(v))
      case _ => None
    } 
  }

  val result = 
    Monad[Future].point("Starting Point") >>= 
    f1 >>= 
    f2 >>=
    f3

  result.onComplete { x => 
    x match {
      case Success(value) => println("Success " + value)
      case Failure(ex) => println(ex)
    }  
  }

  Await.result(result, 1 seconds)
}

最后,如果您只是想要在所有已成功的独立操作之后绑定并行操作,则可以使用scalaz applicative builder:

  val result = (
    Future { 10 + 10 } |@| 
    Future { 20 - 3 } |@| 
    Future { Math.PI * 15 }
  ) { _ + _ / _}
  println(Await.result(result, 1 seconds))

这将让所有3个期货完成,然后将块应用于3个参数。

答案 1 :(得分:1)

实际上答案很简单。

for { 
a <- b
c <- a.get
} yield c.get + 10

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

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

答案 2 :(得分:0)

我还没有使用它们,但它们应该是你正在寻找的东西:Monad变形金刚。

基本上,monad变换器接受Monad(例如Future)并为其添加功能,例如Option提供的功能,并返回转换后的Monad。我认为Scalaz中甚至还有一个Option Monad变换器。这应该允许你在Futures中使用嵌套的选项,并且仍然使用用于理解的平面代码结构。

有关示例,请参阅http://blog.garillot.net/post/91731853561/a-question-about-the-option-monad-transformerhttps://softwarecorner.wordpress.com/2013/12/06/scalaz-optiont-monad-transformer/