title: Scala - Execute arbitrary number of Futures sequentially but dependently
body: <p>I'm trying to figure out the neatest way to execute a series of Futures in sequence, where one Future's execution depends on the previous. I'm trying to do this for an arbitrary number of futures.</p>
  
  <p>User case:</p>
  
  <ul>
  <li>I have retrieved a number of Ids from my database.</li>
  <li>I now need to retrieve some related data on a web service.</li>
  <li>I want to stop once I've found a valid result.</li>
  <li>I only care about the result that succeeded. </li>
  </ul>
  
  <p>Executing these all in parallel and then parsing the collection of results returned isn't an option. I have to do one request at a time, and only execute the next request if the previous request returned no results. </p>
  
  <p>The current solution is along these lines. Using foldLeft to execute the requests and then only evaluating the next future if the previous future meets some condition.</p>
  
  <pre><code>def dblFuture(i: Int) = { i * 2 }
  val list = List(1,2,3,4,5)
  val future = list.foldLeft(Future(0)) {
    (previousFuture, next) =&gt; {
      for {
        previousResult &lt;- previousFuture
        nextFuture &lt;- { if (previousResult &lt;= 4) dblFuture(next) else previousFuture }
      } yield (nextFuture)
    }
  }
  </code></pre>
  
  <p>The big downside of this is a) I keep processing all items even once i've got a result i'm happy with and b) once I've found the result I'm after, I keep evaluating the predicate. In this case it's a simple if, but in reality it could be more complicated.</p>
  
  <p>I feel like I'm missing a far more elegant solution to this. </p>