gpt4 book ai didi

scala - 为什么 Future 的 andThen 不链接结果?

转载 作者:行者123 更新时间:2023-12-03 11:54:54 25 4
gpt4 key购买 nike

andThen意思是我从中学到了answer是一个函数 Composer 。

比如说

f andThen g andThen h

将等于
h(g(f(x)))

这意味着 h function将接收来自 g(f(x)) 的输入

但是对于 andThenFuture , 后面的所有闭包 andThen 总是从原来的 Future 接收结果.
Future{
1
}.andThen{ case Success(x) =>
println(x) // print 1
Thread.sleep(2000)
x * 2
}.andThen{ case Success(x) =>
println(x) // print 1
Thread.sleep(2000)
x * 2
}

相比于
val func: Function1[Int, Int] = { x: Int =>
x
}.andThen { y =>
println(y) // print 1
y * 2
}.andThen { z =>
println(z) // print 2
z * 2
}
func(1)

是什么原因让 Future::andThen(s) 从原始 Future 而不是链接 Future 接收所有相同的结果?我观察到这些链接的 andThen 将按顺序执行,因此原因可能不是出于并行目的。

最佳答案

scala.concurrent.Future被设计为两种异步方法的折衷方案:

  • 面向对象observer允许绑定(bind)异步处理程序
  • 功能 monad它提供了丰富的功能组合能力。

  • 阅读 Future.andThen 's docs :

    Applies the side-effecting function to the result of this future, and returns a new future with the result of this future.



    所以 andThen最有可能来自 OOP 世界。获得与 Function1.andThen 类似的结果你可以使用 map 方法 :
    Future(1).map {_ * 2}.map {_ * 2}
    andThen不同于 onComplete用一件小事: andThen 的 future 仍然返回相同的结果,但会等到提供的观察者返回或抛出一些东西。这就是为什么在文档中写的:

    This method allows one to enforce that the callbacks are executed in a specified order.



    另请注意文档中的第三行:

    Note that if one of the chained andThen callbacks throws an exception, that exception is not propagated to the subsequent andThen callbacks. Instead, the subsequent andThen callbacks are given the original value of this future.



    所以它对新的 Future 完全没有任何作用的结果。甚至不能用它自己的异常(exception)来破坏它。这个 andThenonComplete只是观察者的顺序和并行绑定(bind)。

    关于scala - 为什么 Future 的 andThen 不链接结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30659427/

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