Scala从onComplete返回值

时间:2015-09-01 14:59:20

标签: scala

如何在Scala中构造onComplete以这种方式运行:

图。 1

# ************************************
# Vhost template in module puppetlabs-apache
# Managed by Puppet
# ************************************

<VirtualHost *:80>
  ServerName somesite.de

  ## Vhost docroot
  DocumentRoot "/var/www/somesite"

  ## Directories, there should at least be a declaration for      /var/www/somesite/public

  <Directory "/var/www/somesite">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Require all granted
  </Directory>

  ## Load additional static includes

  ## Logging
  ErrorLog "/var/log/apache2/somesite_http_error.log"
  ServerSignature Off
  CustomLog "/var/log/apache2/somesite_http_access.log" combined

  ## Server aliases
  ServerAlias www.somesite.de

  ## SetEnv/SetEnvIf for environment variables
  SetEnv APP_ENV dev

  ## Custom fragment
  ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/somesite/$1
</VirtualHost>

我以为我可以这样做:

图。 2

{ 
  var x; 
  if(result.isFailure){
    x = foo() // foo is a future
  }

  if(result.isSuccess){
    x = 5
  }  
  bar(x)
}

但onComplete,onFailure和onSuccess都有var x = foo onComplete { case Success(x) => 5 case Failure(t) => foo() //foo is a future } bar(x) 作为返回类型,

Unit

如何在不使用var?

的情况下实现二维形式

2 个答案:

答案 0 :(得分:12)

不鼓励通过等待来自未来的结果来阻止当前线程。相反,您应该在处理result future的结果时调用bar()函数。

result map {r =>
   5
} recover {
   case _ => foo()
} map {r => 
   bar(r)
}

答案 1 :(得分:6)

您可以通过

实现目标
val x: Future[Int] = foo.map(x => 5).recover{case f => foo()}
// do some more work with your future
x.map(bar(_))

假设foo: Future[_]foo(): Int