使用for-comp处理期货,但是if子句使事情变得困难 [英] Handling futures with for-comp, but if clauses are making things difficult

查看:65
本文介绍了使用for-comp处理期货,但是if子句使事情变得困难的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现我遇到了以下模式分配问题,无法正常工作或外观风格不佳.

I find that I am running into the below pattern allot and I can't get it to work or look nice style wise.

我有一个理解,那就是返回期货,然后建立模型以在视图中显示.但是在我将Action返回到结果之前,有时必须使用if子句进行分支,并可能加载更多数据.

I have a for comprehension that is return Futures, and then I build my model to display in a view. But before I return the Result in my Action, I sometimes have to branch using an if clause and potentially load more data.

下面的代码当前无法编译,您如何建议我使用以下类型的模式使下面的代码遵循正确的样式?

The below code doesn't compile currently, what do you suggest I do to make the below code follow correct style with this type of pattern?

它无法编译,因为compr的内部返回了Future [Option [Something]],但我已将c定义为Option [Something]

It doesn't compile because the inner for compr is return a Future[Option[Something]] but I have defined c as Option[Something]

for {
  a <- fooService.getA()
  b <- fooService.getB()
} yield {
  var c: Option[Something] = None
  if(a.size > 0) {
    c = for {
      c <- fooService.getC()
    } yield {
      Some(c)
    }
  }
}
val model = FooModel(a, b, c)
Ok(views.html.foo.show(model))

我的视图模型定义为:

FooModel(a: A, b: B, c: Option[Something])

推荐答案

这似乎很清楚:

for {
  a <- fooService.getA()
  b <- fooService.getB()
  c <- if (a.nonEmpty) fooService.getC() else Future.successful(None)
} yield {
  val model = FooModel(a, b, c)
  Ok(views.html.foo.show(model))
}

如果需要,将if (a.nonEmpty) fooService.getC() else Future.successful(None)提取到另一种方法或服务中.

Extract the if (a.nonEmpty) fooService.getC() else Future.successful(None) to another method or service if you want.

这篇关于使用for-comp处理期货,但是if子句使事情变得困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆