【问题标题】:How to fail an akka promise?如何使 akka 承诺失败?
【发布时间】:2012-06-28 15:19:16
【问题描述】:

假设我有这样的功能(我用的是akka 2.0.2):

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

函数的调用者将onSuccessonFailure 设置为future 挂钩,所以如果我想让演员违背承诺,我让它将akka.actor.Status.Failure 发送回发送者。这工作得很好。现在,如果我想检查foo 中的某些条件并在条件失败/成功的情况下返回失败的未来怎么办?

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

“返回失败的未来”块应该是什么样的?我需要一个执行上下文来实现它吗?

【问题讨论】:

    标签: scala akka future


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-07-23
      • 2017-11-01
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多