我想做大量的外部服务调用,每个跟进了异常处理和有条件的进一步处理。我认为使用.onComplete内部扩展这个很好的示例(Asynchronous IO in Scala with futures)很容易,但似乎我并不了解有关范围和/或期货的内容。任何人都可以指出我正确的方向吗?异步处理使用列表的斯卡拉期货与onComplete异常处理
#!/bin/bash
scala -feature $0 [email protected]
exit
!#
import scala.concurrent.{future, blocking, Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.util.{Success, Failure}
import scala.language.postfixOps
val keylist = List("key1", "key2")
val myFuts: List[Future[String]] = keylist.map {
myid => future {
// this line simulates an external call which returns a future (retrieval from S3)
val myfut = future { Thread.sleep(1); "START " + myid}
var mystr = "This should have been overwritten"
myfut.onComplete {
case Failure(ex) => {
println (s"failed with error: $ex")
mystr = "FAILED"
}
case Success(myval) => {
mystr = s"SUCCESS $myid: $myval"
println (mystr)
}
}
mystr
}
}
val futset: Future[List[String]] = Future.sequence(myFuts)
println (Await.result(futset, 10 seconds))
我的电脑(斯卡拉2.10.4)上
,这个打印:
SUCCESS key2: START key2
SUCCESS key1: START key1
List(This should have been overwritten, This should have been overwritten)
我想(顺序不重要):
SUCCESS key2: START key2
SUCCESS key1: START key1
List(SUCCESS key2: START key2, SUCCESS key1: START key1)
工程很好。 .recover方法是该模式的关键。我没有意识到可以做到这一点。非常感谢! –
对于那些感兴趣的人,这个答案和更有效的替代方法在http://stackoverflow.com/a/15776974/29771中给出。 – Glenn