【问题标题】:Play Framework return result from Twitter FutureTwitter Future 的 Play Framework 返回结果
【发布时间】:2014-10-21 18:55:49
【问题描述】:

我有一个下一个代码,这个返回true,当数字为0时,否则异常

  import com.twitter.util.Future 

  def compute(x: Int): Future[Boolean] = {
     if (x == 0) {
       Future.value(true)
     } else {
       Future.value(new Exception("Invalid number"))
     }
  }  

我的控制器使用此代码:

 object MyController extends Controller {

   def get(x: Int) = Actrion {
     compute(x).flatMap {
       case x: Boolean => Ok(views.html.ok("ok"))
       case _ => NotFound 
     }
   }  
 }

但是当我运行这段代码时,我得到type mismatch; found : play.api.mvc.Result required: com.twitter.util.Future[?]

如何从Future 中提取值并作为结果传递给响应?

【问题讨论】:

    标签: scala playframework-2.0


    【解决方案1】:

    Play 使用 Scala 期货,而不是 Twitter 期货。如果你必须使用 Twitter 的未来,你必须转换它。以下代码取自Akka feature request

    import scala.concurrent.{Future, Promise}
    import com.twitter.util.{Future => TwitterFuture, Throw, Return}
    
    def fromTwitter[A](twitterFuture: TwitterFuture[A]): Future[A] = {
      val promise = Promise[A]()
      twitterFuture respond {
        case Return(a) => promise success a
        case Throw(e) => promise failure e
      }
      promise.future
    }
    

    然后在你的控制器中使用它:

    object MyController extends Controller {true
      def get(x: Int) = Action.async {
        fromTwitter(compute(x)).map { _ =>
          Ok(views.html.ok("ok")) 
        }.recover { case e =>
          NotFound
        }
      }  
    }
    

    您的 case 语句也没有意义,输入布尔值的 Future 将始终导致布尔值。如果未来失败,您可以使用recoverrecoverWithfallbackTo

    【讨论】:

    • 看起来他不想使用 Action.async。只是从未来中提取价值
    【解决方案2】:

    根据Future doc 错误是由于flatMap 定义引起的。我宁愿使用mappoll 方法。

    此外,我建议像这样将scala.concurrent.Future 与 Action.async 一起使用:

    def index = Action.async {
      val futureInt = scala.concurrent.Future { intensiveComputation() }
      futureInt.map(i => Ok("Got result: " + i))
    }
    

    更多信息可以找到here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 2013-12-15
      相关资源
      最近更新 更多