繁体   English   中英

Scala-如何在映射Seq时调用未来函数?

[英]Scala - How to call a future function while mapping over a Seq?

我有一个Seq[String] ,并且需要这些字符串值来调用定义为以下内容的另一个函数:

def getSomethingById(id: String): Future[Someting]

我正在尝试创建一个使用Seq[String]并返回Future[Seq[Something]]的函数;

def getSomethings(ids: Seq[String]): Future[Seq[Something]]

获取Something类型的唯一方法是调用上面的getSomethingById方法。

有没有一种方法可以映射Seq[String] ,然后调用getSomethingById

您可以为此使用Future.sequence

def getSomethings(ids: Seq[String]): Future[Seq[Something]] =
  Future.sequence(ids.map(getSomethingById))

https://www.scala-lang.org/api/current/scala/concurrent/Future%24.html

Future.traverse的简单版本。 异步且非阻塞地将TraversableOnce [Future [A]]转换为Future [TraversableOnce [A]]。 对于将许多期货简化为单个期货很有用。

除了现有答案,您还可以使用Future.traverse ,这非常相似

scala> import scala.concurrent.Future
       import scala.concurrent.ExecutionContext.Implicits.global


def getSomethingById(id: String): Future[String] = Future{
  id + "from Something Id"
}

def getSomethings(ids: Seq[String]): Future[Seq[String]] = 
       Future.traverse(ids)(getSomethingById)

scala> getSomethingById: (id: String)scala.concurrent.Future[String]
scala> getSomethings: (ids: Seq[String])scala.concurrent.Future[Seq[String]]

测试

scala> getSomethings(Range.apply(1,3).map(_.toString))
res0: Vector(1from Something Id, 2from Something Id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM