【问题标题】:How to avoid next functions in the pipeline while using futures如何在使用期货时避免管道中的下一个功能
【发布时间】:2020-01-09 09:57:45
【问题描述】:

根据未来值的当前结果停止/跳过以下函数的最佳方法是什么?

假设我有 3 个返回 Future[Boolean] 的函数,如下所示:

def funA() : Future[Boolean] = Future(true) 
def funB() : Future[Boolean] = Future(false) 
def funC() : Future[Boolean] = Future(true) 

当我从funB 得到false 时,我需要避免调用funC

编辑

  1. 当当前函数失败时,使用之前成功的函数恢复。

    • 在当前场景中,当funB 失败时返回funA 的结果,即true
  2. 只要没有失败就需要执行所有的功能。

    • 在当前场景中,如果funB 返回true,则funC 返回值是所有调用的结果。

【问题讨论】:

    标签: scala future


    【解决方案1】:

    您可以使用带有 if 语句的 for 理解来做到这一点。当funB 为 false 时,不清楚您希望结果是什么,因此如果您想要默认的成功值,可以将 Future.failed 替换为成功:

    for {
      result1 <- funA()
      result2 <- funB()
      result3 <- if(result2) funC() else Future.failed(new Exception("funB was false"))
    } yield {
      "Completed!"
    }
    

    【讨论】:

      【解决方案2】:

      一个不那么紧凑但(希望如此!)更具教育意义的例子:

      it("Future chain evaluation") {
        var aWasCalled = false
        var bWasCalled = false
        var cWasCalled = false
      
        def futureA = Future {
          aWasCalled = true
          true
        }
      
        def futureB = Future {
          bWasCalled = true
          false
        }
      
        def futureC = Future {
          cWasCalled = true
          true
        }
      
        val futureEvaluationResult = futureA.flatMap { a =>
          if (!a) Future.successful(false)
          else {
            futureB.flatMap { b =>
              if (!b) Future.successful(false)
              else futureC
            }
          }
        }
      
        futureEvaluationResult.map { evaluationResult =>
          evaluationResult shouldBe false
        }
      
        aWasCalled shouldBe true
        bWasCalled shouldBe true
        cWasCalled shouldBe false
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多