【问题标题】:Returning Future of Future in Play for Scala在 Scala 中回归未来的未来
【发布时间】:2017-06-24 04:13:35
【问题描述】:

在下面的代码中,我必须返回在另一个未来之后调用的未来的结果。我在future2.map 行中收到以下错误:

类型不匹配;发现:scala.concurrent.Future[play.api.mvc.Result] 必需:play.api.mvc.Result

如何做到这一点?

def method1 = Action.async { request => 
    val future1 = f1
    future1.map { result1 =>
          val future2 = f2
          future2.map { result2 =>
              Ok(result1+result2+"")
          }
    }
}

def f1 = Future { 1 }
def f2 = Future { 2 }

【问题讨论】:

    标签: scala playframework


    【解决方案1】:

    您可以通过多种方式做到这一点。但首先,您需要了解mapflatMap 如何与Future 一起使用:

    def map[S](f: (T) ⇒ S): Future[S]
    def map[S](f: (T) ⇒ Future[S]): Future[Future[S]]
    def flatMap[S](f: (T) ⇒ Future[S]): Future[S]
    

    请注意,在上述签名中,您正在调用 mapflatMap,其值为 already is a future,即 Future[<some-value>].map(...)Future[<some-value>].flatMap(...)

    方法一:

        def method1 = Action.async { request =>
        val future1 = f1
        future1.flatMap { result1 => //replaced map with flatMap
          val future2 = f2
          future2.map { result2 =>
            Ok(result1+result2+"")
          }
        }
      }
    
      def f1 = Future { 1 }
      def f2 = Future { 2 }
    

    方法2:

    def method1 = Action.async { request =>
        val future1 = f1
        future1.flatMap { result1 => //replaced map with flatMap
          val future2 = f2
          future2.flatMap { result2 => //replaced map with flatMap
            Future.successful{Ok(result1+result2+"")} // used Future.successful{} to generate a Future of Result
          }
        }
      }
    
      def f1 = Future { 1 }
      def f2 = Future { 2 }
    

    【讨论】:

    • 方法 2 通过将结果包围在成功的 Future 中增加了不必要的复杂性。尽管您可以做到这一点,但绝对没有理由更喜欢第一个。
    • 是的,我同意。我试图说明mapflatMap 如何与未来一起工作的不同方式。当我们必须在未来计算中处理多个案例时,Future.successful() 是不可避免的,其中一个案例返回Future(value),另一个案例返回@987654337仅限@。
    【解决方案2】:

    future1.map 更改为future1.flatMap 应该可以解决问题。映射 Future 会返回另一个 Future 并更改其中的值。在这种情况下,您将返回一个 Future,其中包含 另一个 Future,其中包含一个 Result。通过使用flatMap,它实质上将嵌套的Future[Future[Result]] 扁平化为Future[Result]

    【讨论】:

      猜你喜欢
      • 2018-03-18
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 2018-06-17
      • 2013-05-13
      • 2018-06-23
      相关资源
      最近更新 更多