gpt4 book ai didi

scala - 运行 future n 次

转载 作者:行者123 更新时间:2023-12-05 04:17:56 27 4
gpt4 key购买 nike

我想运行我 future 的调用 n 次,例如 5。 future 的“执行”将需要一些时间,我只想在上一个完成时调用新的调用。像这样的东西:

def fun(times: Int): Future[AnyRef] = {
def _fun(times: Int) = {
createFuture()
}

(1 to times).foldLeft(_fun)((a,b) => {
println(s"Fun: $b of $times")
a.flatMap(_ => _fun)
})
}

所以我想一个一个地调用“_fun”函数n次。 “createFuture()”需要一些时间,因此在之前的 future 完成之前不应再次调用“_fun”。另外,我想创建一个非阻塞解决方案。目前,此代码无需等待以前的 future 结束即可执行。

有什么想法可以让它发挥作用吗?

感谢您的回答!

最佳答案

如果不了解你究竟希望最终的 future 返回什么(我将只返回最后完成的 future 的结果),你可以尝试这样的事情:

def fun(times: Int): Future[AnyRef] = {
val prom = Promise[AnyRef]()
def _fun(t: Int) {

val fut = createFuture()
fut onComplete {
case Failure(ex) => prom.failure(ex)
case Success(result) if t >= times => prom.success(result)
case Success(result) => _fun(t + 1)
}

}
_fun(1)

prom.future
}

这是一种递归解决方案,在完成时将 futures 链接在一起,在达到最大次数时停止链接。这段代码并不完美,但肯定传达了一种可能的解决方案,以确保在前一个 future 成功完成之前,连续的 futures 不会触发。

关于scala - 运行 future n 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19248881/

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