title: How to chain Scala Futures with timeouts?
body: <p>Suppose I've got a few functions that return <code>Future</code>:</p>
  <pre><code>def fab(a: A, timeOutMillis: Long): Future[B] = ???
  def fbc(b: B, timeOutMillis: Long): Future[C] = ???
  def fcd(c: C, timeOutMillis: Long): Future[D] = ???
  </code></pre>
  <p>If <code>timeOutMillis &gt; 0</code> the functions return futures that complete within <code>timeOutMillis</code> period of time. Otherwise they return a failed <code>Future</code>.</p>
  <p>Now I want to compose these functions to write <code>fac</code> and <code>fad</code>:</p>
  <pre><code>def fac(a: A, timeOutMillis: Long): Future[C] = ???
  def fad(a: A, timeOutMillis: Long): Future[D] = ???
  </code></pre>
  <p>So I can implement <code>fac</code> like this:</p>
  <pre><code>def fac(a: A, timeOutMillis: Long): Future[C] = {
    val startTime = System.currentTimeMillis()
    for {
       b &lt;- fab(a, timeOutMillis)
       timeAB = System.currentTimeMillis() - startTime
       c &lt;- fbc(b, timeOutMillis - timeAB)
    } yield c
  }
  </code></pre>
  <p>Note I don't want to <em>wait</em> for completion of futures, therefore I don't use <code>Await</code>.</p>
  <p>This <code>fac</code> implementation will probably work but it looks clumsy and contains boilerplate code.<br />
  How would you suggest chain <code>Futures</code> with timeouts ?</p>
  <p>P.S. I'm thinking about overriding <code>flatMap</code> of <code>Future</code> to calculate the next timeout. What do you think ?</p>