【发布时间】:2019-08-12 08:55:39
【问题描述】:
我遇到了一个问题,我的未来(用 OptionT 包裹)没有完成。
当我在没有 OptionT 的情况下明确等待结果时,我可以看到正确的输出(参见 Some(2,2) 下面的日志)。但在我的理解中,我们从来没有看到“Ids:”日志。而在 Await OptionT println 中,我们永远看不到输出。
显然没有 Duration.Inf,期货超时。
这里的功能是,如果提供的 ID 的品牌和国家不存在,我们应该失败。如果它们存在,我们可以继续在它们之间创建链接。
def save(brandId: Int, countryId: Int): Future[Option[Int]] = {
val now = DateTime.now(DateTimeZone.UTC)
println(s"Await: ${Await.result(getIds(brandId, countryId), Duration.Inf)}")
println(s"Await OptionT: ${Await.result(OptionT(getIds(brandId, countryId)).map(identity).value, Duration.Inf)}")
for {
ids <- OptionT(getIds(brandId, countryId))
_ = logger.info(s"Ids: $ids")
brand = BrandCountry(None, ids._2, ids._1, now, "admin", now, "admin")
_ = logger.info(s"Brand: $brand")
insertStmt = BrandCountrys.returning(BrandCountrys.map(_.id)) += brand
_ = logger.info(s"Executing SQL:\n${insertStmt.statements.mkString(";\n")}")
result <- OptionT.liftF(db.run(insertStmt))
} yield result
}.value
private def getIds(brandId: Int, countryId: Int) = {
val ids = for {
bId <- Brands.filter(_.id === brandId).map(_.id)
cId <- Countries.filter(_.id === countryId).map(_.id)
} yield (bId, cId)
logger.info(s"Executing SQL:\n${ids.result.statements.mkString(";\n")}")
db.run(ids.result.headOption)
}
这里的日志输出是
[error] c.d.d.v.d.BrandCountrysDao - Executing SQL:
select x2."id", x3."id" from "configurations_v2"."brands" x2, "configurations_v2"."countries" x3 where (x2."id" = 2) and (x3."id" = 2)
Await: Some((2,2))
[error] c.d.d.v.d.BrandCountrysDao - Executing SQL:
select x2."id", x3."id" from "configurations_v2"."brands" x2, "configurations_v2"."countries" x3 where (x2."id" = 2) and (x3."id" = 2)
然后它会永远等待 (Duration.Inf)
【问题讨论】:
标签: scala slick future option scala-cats