0

我正在使用 scala 并将我的域对象写入 json。我像这样使用 Play 的 Json 组合器:

implicit def opensHighlights: Writes[Option[OpensHighlights]] =
  (
    (__ \ 'header).write[String] and
    (__ \ 'topDeviceForOpens).write[String] and
    (__ \ 'percentage).write[String] and
    (__ \ 'percentageOf).write[String])(opensMaybe => {
      val header = Messages("email.summary.highlights.device.opens")
      val percentageOf = Messages("email.summary.highlights.ofAll.opens")
      opensMaybe match {
        case Some(opens) => (
          header,
          deviceTypeName(opens.topDevice),
          Percentage(opens.opensOnThisDevice, opens.totalOpens).stringValue(),
          percentageOf)
        case None => (header, NotApplicable, "0.00", percentageOf)
      }
    })

我在一个更大的作家中使用这个作家:

implicit def summaryHighlightsWrites: Writes[SummaryHighlights] = {
      (
        (__ \ "google").write[Either[GoogleError, GoogleHighlights]] and
        (__ \ "dateWithHighestClickToOpenRate").write[Option[DateHighlights]] and
        (__ \ "subjectLine").write[Option[SubjectLineHighlights]] and
        (__ \ "location").write[Option[LocationHighlights]] and
        (__ \ "link").write[Option[LinkHighlights]] and
        (__ \ "deviceForOpens").write[Option[OpensHighlights]] and
        (__ \ "deviceForClicks").write[Option[ClicksHighlights]])(summary => {
          val result = for {
            google <- summary.google
            dateRange <- summary.dateRange
            subjectLine <- summary.subjectLine
            location <- summary.location
            link <- summary.link
            opensDevice <- summary.opensDevice
            clicksDevice <- summary.clicksDevice
          } yield (google, dateRange, subjectLine, location, link, opensDevice, clicksDevice)

          Await.result(result, 10 seconds)
        })
    }

这是 SummaryHighlights 类:

case class SummaryHighlights(
  google: Future[Either[GoogleError, GoogleHighlights]],
  dateRange: Future[Option[DateHighlights]],
  subjectLine: Future[Option[SubjectLineHighlights]],
  location: Future[Option[LocationHighlights]],
  link: Future[Option[LinkHighlights]],
  opensDevice: Future[Option[OpensHighlights]],
  clicksDevice: Future[Option[ClicksHighlights]])

我需要这些字段每个都是一个Future,因为它们有独立的来源并且可以独立失败/成功。

我想删除那个明确的等待。我想将未来的等待从summaryHighlightsWrites调用该作者的其他代码中转移。就像一个播放控制器。

有什么帮助吗?谢谢

4

1 回答 1

3

假设您有一个highlights返回 a 的方法,Future[Option[OpensHighlights]]并且您在范围内定义了一个隐式Writes[Option[OpensHighlights]]in,您将执行以下操作:

def highlights: Future[Option[OpensHighlights]] = ...

def asyncJson = Action.async { request =>
    highlights.map { result =>
        Ok(Json.toJson(result))
    }
}

Future[...]必须映射到返回的Future[Result]within Action.async,它将专门处理Future[Result]s 而不是普通Result的 s。

于 2014-10-30T13:34:52.923 回答