gpt4 book ai didi

scala - 如何让 akka promise 失败?

转载 作者:行者123 更新时间:2023-12-02 22:37:34 24 4
gpt4 key购买 nike

假设我有这样一个函数(我使用 akka 2.0.2):

def foo(message: String): Future[SomeClass] =
for {
result <- actor ? message
} yield SomeClass(result)

函数的调用者在未来设置了onSuccessonFailure 钩子(Hook),所以如果我想让参与者违反 promise ,我让它发送akka .actor.Status.Failure 返回给发送者。那很好用。现在,如果我想检查 foo 中的某些条件并在条件失败/成功时返回失败的 future 怎么办?

def foo(message: String): Future[SomeClass] =
if(...) {
...//return failed future
} else {
for {
result <- actor ? message
} yield SomeClass(result)
}

“返回失败的 future ” block 应该是什么样的?我是否需要执行上下文来实现它?

最佳答案

只需返回一个表达式:Promise.failed(new Exception),其中异常是您希望 future 失败的异常。如果您在 Scala standard library from 2.10 中使用 Scala future 和 promise ,则不需要执行上下文。 .

Akka futures and promises failed promise 方法需要隐式执行上下文。 execution context companion object 中应该有一个可用的默认执行上下文,如果您有一个可用的 ActorSystem 实例,您就可以使用它。

关于scala - 如何让 akka promise 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11222029/

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