I would avoid using onComplete
and trying to use it to do side-effecting logic on a mutable variable. I would instead map the future and handle the fail case as returning a different value. Here's a slightly modified version of your code, using map
on the Future
(via a for comprehension) and then using recover
to handle the failure case. Hopefully this is what you were looking for:
val keylist = List("key1", "key2")
val myFuts: List[Future[String]] = keylist.map {myid =>
// this line simulates an external call which returns a future (retrieval from S3)
val myfut = future { Thread.sleep(1); "START " + myid}
val result = for (myval <- myfut) yield {
val res = s"SUCCESS $myid: $myval"
println(res)
res
}
result.recover{
case ex =>
println (s"failed with error: $ex")
"FAILED"
}
}
val futset: Future[List[String]] = Future.sequence(myFuts)
println (Await.result(futset, 10 seconds))