Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala和Play framework 2.2.0、Action.async和isAuthenticated_Scala_Asynchronous_Playframework 2.0 - Fatal编程技术网

Scala和Play framework 2.2.0、Action.async和isAuthenticated

Scala和Play framework 2.2.0、Action.async和isAuthenticated,scala,asynchronous,playframework-2.0,Scala,Asynchronous,Playframework 2.0,我有一个应用程序使用zentasks示例中描述的isAuthenticated模式。 它还使用Future/Async来最小化阻塞 def index = isAuthenticated { username => implicit request => val promise = Future { Foo.all() } Async { promise.map(f => Ok(v

我有一个应用程序使用zentasks示例中描述的isAuthenticated模式。 它还使用Future/Async来最小化阻塞

  def index = isAuthenticated { username => implicit request =>        
    val promise = 
      Future {
        Foo.all()    
      }
    Async {
      promise.map(f => Ok(views.html.foo.index(username, f)))
    }        
  }
这在Play 2.2.0中仍然有效,但不推荐使用Future/Async模式。我们应该使用Action.async;比如:

  def asyncTest = Action.async {
    val fut = Future {
      // Artificial delay to test.
      Thread.sleep(5000)
      "McFly"
    }
    fut.map (f => Ok(f))      
  }

我的问题是,;如何将Action.async与上述身份验证方法或类似方法结合使用?

一个选项是通过定义
IsAuthenticated
来使用,如下所示:

def username(request: RequestHeader) = request.session.get("email")

def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Application.login)

def IsAuthenticated(f: => String => Request[AnyContent] => Future[SimpleResult]) = {
  Action.async { request =>
    username(request).map { login =>
      f(login)(request)        
    }.getOrElse(Future.successful(onUnauthorized(request)))
  }
}
然后你可以用以下方式使用它:

def index = IsAuthenticated { user => implicit request =>
  val fut = Future {
    // Artificial delay to test.
    Thread.sleep(5000)
    "McFly"
  }
  fut.map (f => Ok(f))      
}

工作完美,让我深入了解这些东西的实际工作原理。谢谢