title: asynchronous processing using list of Scala futures with onComplete for exception handling
body: <p>I'm trying to make a large number of external service calls, each followed up with exception handling and conditional further processing.  I thought it would be easy to extend this nice (<a href="https://stackoverflow.com/questions/13097754/asynchronous-io-in-scala-with-futures">Asynchronous IO in Scala with futures</a>) example using an .onComplete inside, but it appears that I don't understand something about scoping and/or Futures.  Can anyone point me in the right direction please?</p>
  
  <pre><code>#!/bin/bash
  scala -feature $0 $@
  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 =&gt; 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) =&gt; {
          println (s"failed with error: $ex")
          mystr = "FAILED"
        }
        case Success(myval) =&gt; {
          mystr = s"SUCCESS $myid: $myval"
          println (mystr)
        }
      }
      mystr
    }
  }
  
  val futset: Future[List[String]] = Future.sequence(myFuts)
  println (Await.result(futset, 10 seconds))
  </code></pre>
  
  <p>on my computer (Scala 2.10.4), this prints:</p>
  
  <pre><code>SUCCESS key2: START key2
  SUCCESS key1: START key1
  List(This should have been overwritten, This should have been overwritten)
  </code></pre>
  
  <p>I want (order unimportant):</p>
  
  <pre><code>SUCCESS key2: START key2
  SUCCESS key1: START key1
  List(SUCCESS key2: START key2, SUCCESS key1: START key1)
  </code></pre>