title: Reduce Future sequentially in vert.x
body: <p>In my project I am using the <code>Future</code> implementation of vert.x in Java. So far everything went fine. However, currently I have problems executing an action on a list of objects sequentially. The problem lies in the <code>reduce</code> method "reducing" and "combining" results seperately in Java. This results in all the actions to be started simultaneously. Achieving sequential execution is possible, as one can see in the <code>easy</code> method.</p>
  
  <pre><code>private Future&lt;Void&gt; action(String object) {
      System.out.println("started " + object);
      Future&lt;Void&gt; f = Future.future();
      vertx.setTimer(1000, res -&gt; {
          System.out.println("doing " + object);
          f.complete();
      });
      return f;
  }
  
  private void easy() {
      action("one")
          .compose(ignore -&gt; action("two"))
          .compose(ignore -&gt; action("three"))
          .setHandler(ignore -&gt; System.out.println("completed"));
  }
  
  private void list() {
      List&lt;String&gt; l = new ArrayList&lt;&gt;();
      l.add("one");
      l.add("two");
      l.add("three");
  
      Future&lt;Void&gt; f = Future.future();
      l.stream().reduce(f,
          (f1, s) -&gt; action(s),
          (f1, f2) -&gt; f2.compose(ignore -&gt; f1)
      ).setHandler(res -&gt; {
          System.out.println("completed");
      });
  }
  </code></pre>
  
  <p>Output when executing easy:</p>
  
  <pre><code>started one
  doing one
  started two
  doing two
  started three
  doing three
  completed
  </code></pre>
  
  <p>Ouput when executing list:</p>
  
  <pre><code>started one
  started two
  started three
  doing one
  doing two
  doing three
  completed
  </code></pre>
  
  <p>The same snippet in Javascript works, as the reduce function does reducing and combining in one step:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function action(object) {
    return new Promise((resolve, reject) =&gt; {
      console.log("started " + object)
      window.setTimeout(() =&gt; {
        console.log("doing " + object);
        resolve()
      }, 1000);
    });
  }
  
  function easy() {
    action("one")
      .then(() =&gt; action("two"))
      .then(() =&gt; action("three"))
      .then(() =&gt; console.log("completed"));
  }
  
  function list() {
    l = ["one", "two", "three"]
    l.reduce((p, s) =&gt; p.then(() =&gt; action(s)), Promise.resolve())
      .then(() =&gt; console.log("completed"));
  }
  
  // easy()
  list()</code></pre>
  </div>
  </div>
  </p>
  
  <p>Output for <code>easy</code> and <code>list</code> is same as easy method of Java code. What I am looking for, is a way to fix the reduce method in Java or an alternative way to achieve the same result.</p>