gpt4 book ai didi

scala - 在 Scala 中回归 future 的 future

转载 作者:行者123 更新时间:2023-12-01 09:16:44 26 4
gpt4 key购买 nike

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

type mismatch; found : scala.concurrent.Future[play.api.mvc.Result] required: 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 }

最佳答案

您可以通过多种方式做到这一点。但首先,您需要了解 mapflatMapFuture 合作:

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 futureFuture[<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 }

关于scala - 在 Scala 中回归 future 的 future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42081021/

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