【问题标题】:How to map two `future` results in Scala/ReactiveMongo?如何在 Scala/ReactiveMongo 中映射两个“未来”结果?
【发布时间】:2016-02-24 14:51:24
【问题描述】:

我有一个使用 Play 和 ReactiveMongo 编写的应用程序,我想:

  • 具有将landingPage 文档插入 MongoDB 的操作。
  • 插入新的landingPage 并等待它插入。
  • 统计新的landingPage文档总数并将其返回给用户。

我有这个工作代码:

// Insert the landing page and wait for it to be inserted, so we can then get the new count of landing pages.
val futures = for {
  wr <- landingPagesCollection.insert(landingPage)
  count <- landingPagesCollection.count()
} yield count

futures.map { (count: Int) =>
  Created(Json.obj(
    "created" -> true,
    "landingPage" -> landingPage.toJson,
    "count" -> count
  ))
}

此代码运行良好。但是,出于好奇,我想知道如何访问 wr (WriteResult) 价值。当我将代码更改为:

val futures = for {
  wr <- landingPagesCollection.insert(landingPage)
  count <- landingPagesCollection.count()
} yield (wr, count)

futures.map { (wr: WriteResult, count: Int) =>
  Created(Json.obj(
    "created" -> true,
    "message" -> s"You created landing page ${landingPage.name} (${landingPage.jobNumber}). The Git URI is '${landingPage.gitUri}'.",
    "landingPage" -> landingPage.toJson,
    "count" -> count,
    "writeResult" -> wr
  ))
}

我收到以下错误消息:

谁能解释一下如何在地图功能中访问wr

【问题讨论】:

    标签: mongodb scala future reactivemongo


    【解决方案1】:

    尝试改变

    futures.map { (wr: WriteResult, count: Int) =>
    

    到:

    futures.map { case (wr: WriteResult, count: Int) =>
    

    或者只是:

    futures.map { case (wr, count) =>
    

    希望对你有帮助

    【讨论】:

    【解决方案2】:

    如果函数接受 2 个参数而不是元组,则您使用的语法有效

    list.map((a: Int, b: String) => ...)
    

    如果你需要一个元组,你可以这样做:

    list.map(tuple: (Int, String) => {
       val (num, str) = tuple
       ...
    })
    

    或按照接受的答案中的建议传递部分函数。它将与参数匹配(它匹配一个元组)并允许您稍后使用提取的值

    list.map { case (a: Int, b: String) => ... }
    

    请注意,在这种情况下,大括号是必需的。

    类型注释可以被删除,因为它们可以被编译器推断出来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2021-07-12
      • 2015-07-02
      相关资源
      最近更新 更多