在喷涂工艺中使用未来 [英] Use Future in Spray Routing

查看:75
本文介绍了在喷涂工艺中使用未来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是异步编程的新手。我阅读了本教程 http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-future.html 和我为将Future集成到程序中而毫不费力地感到惊讶。但是,当我在路由中使用Future时,返回类型有点错误。

I'm new to asynchronous programming. I read this tutorial http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-future.html and was surprised by how effortless I can incorporate Future into the program. However, when I was using Future with Routing, the return type is kind of wrong.

get {
  optionalCookie("commToken") {
    case Some(commCookie) =>
      val response = (MTurkerProgressActor ? Register).mapTo[..].map({...})
      val result = Await.result(response, 5 seconds)

      setCookie(HttpCookie("commToken", content = result._2.mturker.get.commToken)) {
        complete(result._1, result._2.mturker.get)
      }

    case None => // ...
  }
}

我真的不想使用 Await (如果我只是阻塞线程并等待5秒钟,异步的意义何在?)。我尝试将用于 -comprehension或 flatMap 并放置 setCookie complete 动作,但是返回类型对于Spray是不可接受的。理解返回 Unit, flatMap 返回Future。

I really don't want to use Await (what's the point of asynchronous if I just block the thread and wait for 5 seconds?). I tried to use for-comprehension or flatMap and place the setCookie and complete actions inside, but the return type is unacceptable to Spray. For-comprehension returns "Unit", and flatMap returns a Future.

因为我需要设置此Cookie ,我需要里面的数据。 等待是否可以解决?还是有其他方法?

Since I need to set up this cookie, I need the data inside. Is Await the solution? Or is there a smatter way?

推荐答案

您可以使用 onSuccess 指令:

get {
    optionalCookie("commToken") { cookie =>
      //....
      val response = (MTurkerProgressActor ? Register).mapTo[..].map({...})
      onSuccess(response) {
        case (result, mTurkerResponse) =>
          setCookie(HttpCookie("commToken", content = mTurkerResponse.mturker.get.commToken)) {
            complete(result, mturkerResponse.mturker.get)
          }
      }
    }

还有 onFailure onComplete (必须在成功失败上进行匹配) )请参见 http://spray.io/documentation/1.2.1/spray-routing / future-directives / onComplete /

There's also onFailure and onComplete (for which you have to match on Success and Failure) See http://spray.io/documentation/1.2.1/spray-routing/future-directives/onComplete/

此外,与其直接使用 get ,还不如说是惯用的使用 map (我假设 mturker Option 或类似的内容):

Also, instead of using get directly it's much more idiomatic to use map (I assume the mturker is an Option or something similar):

case (result, mTurkerResponse) =>
  mTurkerResponse.mturker.map { mt =>
    setCookie(HttpCookie("commToken", content = mt.commToken)) {
      complete(result, mt)
    }
  }

这篇关于在喷涂工艺中使用未来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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