gpt4 book ai didi

Scala Future 回调 hell

转载 作者:行者123 更新时间:2023-12-02 10:06:07 25 4
gpt4 key购买 nike

我已经多次阅读有关 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

此代码无法编译

Error:(21, 8) type mismatch; found : Option[Int] required:
scala.concurrent.Future[?] res <- d
^

最佳答案

您可以使用 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 这样的库,并显式使用单子(monad)绑定(bind)来展平事物(编辑编码一些选项类型以解决下面的评论):

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)
}

最后,如果您只想在所有独立的成功之后绑定(bind)并行操作,则可以使用 scalaz 应用构建器:

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

这将使所有 3 个 future 完成,然后将 block 应用于 3 个参数。

关于Scala Future 回调 hell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28343904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com