title: Chaining in CompletableFuture to return first value
body: <p>I have some code that saves an entity to a database using <code>spring-data</code> and then performs some other work <code>foo()</code> and <code>bar()</code> that needs the <code>id</code> from the entity that has been saved. It looks like this:</p>
  
  <pre><code>private CompletableFuture&lt;Void&gt; save(MyEntity me) {
      CompletableFuture&lt;Void&gt; future = ContextAwareCompletableFuture
          .runAsync(() -&gt; repository.save(me))
          .thenRunAsync(() -&gt; foo(me))
          .thenRunAsync(() -&gt; bar(me));
      return future;
  }
  
  private Foo foo(MyEntitiy me) {
      // Use the identifier for me to update some foo in another world
  }
  
  private Bar bar(MyEntitiy me) {
      // Use the identifier for me to update some bar in at another time
  }
  </code></pre>
  
  <p>Now, I do not want to return <code>void</code> from my <code>save</code> method. I want to return a <code>MyEntity</code> so I tried:</p>
  
  <pre><code>private CompletableFuture&lt;MyEntity&gt; save(MyEntity me) {
      CompletableFuture&lt;MyEntity&gt; future = ContextAwareCompletableFuture
          .runAsync(() -&gt; repository.save(me))
          .thenRunAsync(() -&gt; foo(me))
          .thenRunAsync(() -&gt; bar(me));
      return future;
  }
  </code></pre>
  
  <p>This does not work since <code>runAsync</code> returns void. My method <code>repository.save()</code> returns the object I wish to return but that call is at the beginning of the chain. I need to save the object before I can do my <code>foo</code> and <code>bar</code>.</p>
  
  <p>So next thing I tried is:</p>
  
  <pre><code>private CompletableFuture&lt;MyEntity&gt; save(MyEntity me) {
      CompletableFuture&lt;MyEntity&gt; future = ContextAwareCompletableFuture
          .supplyAsync(() -&gt; repository.save(me))
          .thenApplyAsync((e) -&gt; baz(e);
      return future;
  }
  
  private MyEntity baz(MyEntitiy me) {
      foo(me);
      bar(me);
      return me;
  }
  </code></pre>
  
  <p>Now, that seems wrong to me. <code>Foo</code> and <code>Bar</code> will now have to be executed during the same stage and they might take some time.</p>
  
  <p>How can I return the object saved in <code>repository.save()</code> after <code>foo</code> and <code>bar</code> has finished properly?</p>