假设我有一个这样的函数(我使用akka 2.0.2):
def foo(message: String): Future[SomeClass] =
for {
result <- actor ? message
} yield SomeClass(result)
函数的调用者设置了 onSuccess
和 onFailure
Hook future ,所以如果我想让一个 Actor 违背 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 futures 和promise,则不需要执行上下文。 .
Akka futures and promises需要 failed
Promise 方法的隐式执行上下文。 execution context companion object 中应该有一个可用的默认执行上下文。 ,只要您有可用的 ActorSystem
实例,就可以使用它。
关于scala - 如何让 akka promise 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11222029/