当前位置: 首页 > 知识库问答 >
问题:

将 Scala Future[Seq[X]] 与 Seq[Future[Y]] 结合起来,生成 Future[(X,Seq[Y])]

孔安福
2023-03-14

我在我的实体类中具有以下关系,客户 -

type CustomerWithInvoices = (Custimer,Seq[Invoice])

  def findCustomerWitnInvoices:Future[Seq[CustomerWithInvoices]] = {
    for{
      customers <- findCustomers
      eventualInvoices: Seq[Future[Seq[Invoice]]] = customers.map(customer => findInvoicesByCustomer(customer))

    } yield ???
  }

使用现有的存储库方法如下

def findCustomers:Future[Seq[Customers]] = {...}

def findInvoicesByCustomer(customer:Customer):Future[Seq[Invoice]] = {...}

我试图使用如上所述表达方式,但我无法找到正确的方法来做到这一点,因为我对Scala相当陌生,非常感谢任何帮助。


共有1个答案

郗缪文
2023-03-14

我会使用Future.sequence,简化的方法签名是ser sequence采取M[Future[A]]并返回Future[M[A]]这就是我们需要解决你的问题,这是我会写的代码:

val eventualCustomersWithInvoices: Future[Seq[(Customer, Seq[Invoice])]] = for {
      customers <- findCustomers()
      eventualInvoices <- Future.sequence(customers.map(customer => findInvoicesByCustomer(customer)))

    } yield eventualInvoices

请注意,eventualInVoice的类型是Future[Seq[(客户,Seq[发票])]]]因此Future[Seq[Customer withInVoice]]

 类似资料:
  • 我试图使用以下公式将Future[Seq[(String,String)]转换为Future[Seq[(String)]: 所以 sortedSeq 是 Future[Seq[(String, String)]] 但我一直得到错误: 我做错了什么?

  • 我有两个外部呼叫 这给了未来[Seq[人]] 它接受person_id,并将person_status返回为 Future[String] 我需要使用第一次呼叫中可用序列的第二次呼叫来更新每个人的状态。这就是我尝试的方式,

  • 基本上,我想读取Apache Ignite上的查询返回的所有值,该查询返回一个IgniteCursor。 我想以非阻塞的方式读取光标。 我可以写: 也许我错过了什么? 换句话说,有一种方法可以使用“异步非阻塞IO”从Ignite获取记录列表?

  • 描述 (Description) 方法tuple()将项列表转换为元组 语法 (Syntax) 以下是tuple()方法的语法 - tuple( seq ) 参数 (Parameters) seq - 这是一个要转换为元组的序列。 返回值 (Return Value) 此方法返回元组。 例子 (Example) 以下示例显示了tuple()方法的用法。 #!/usr/bin/python aLi

  • 描述 (Description) 方法extend()将seq的内容追加到list。 语法 (Syntax) 以下是extend()方法的语法 - list.extend(seq) 参数 (Parameters) seq - 这是元素列表 返回值 (Return Value) 此方法不返回任何值,但将内容添加到现有列表。 例子 (Example) 以下示例显示了extend()方法的用法。 #!

  • 描述 (Description) 方法list()接受序列类型并将它们转换为列表。 这用于将给定元组转换为列表。 Note - 元组与列表非常相似,唯一的区别是元组的元素值不能更改,元组元素放在括号之间而不是方括号。 语法 (Syntax) 以下是list()方法的语法 - list( seq ) 参数 (Parameters) seq - 这是一个要转换为列表的元组。 返回值 (Return