gpt4 book ai didi

scala - 如何在 Scala 中为 Future 添加回调?

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

我看到一个例子here :

val fut = Future { ... // my body function } // my body function starts herefut onComplete { ... // my callback }

看起来我可以在主体功能完成后添加回调。它仍然被调用吗?无论如何,我更愿意在我的函数开始运行之前向 future 添加回调。是否有意义 ?我该怎么做?

最佳答案

文档非常清楚你的第一点:

If the future has already been completed when registering the callback, then the callback may either be executed asynchronously, or sequentially on the same thread.

至于您的后一个问题——您可以将需要运行的代码作为 future body 的第一行,例如:

def futureWithBefore[T](body: => T, before: => Any) = future {
before()
body()
}

关于scala - 如何在 Scala 中为 Future 添加回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16549418/

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