title: How to synchronize a sequence of promises?
body: <p>I have an array of promise objects that must be resolved in the same sequence in which they are listed in the array, i.e. we cannot attempt resolving an element till the previous one has been resolved (as method <code>Promise.all([...])</code> does).</p>
  
  <p>And if one element is rejected, I need the chain to reject at once, without attempting to resolve the following element.</p>
  
  <p>How can I implement this, or is there an existing implementation for such <code>sequence</code> pattern?</p>
  
  <pre><code>function sequence(arr) {
      return new Promise(function (resolve, reject) {
          // try resolving all elements in 'arr',
          // but strictly one after another;
      });
  }
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>The initial answers suggest we can only <code>sequence</code> results of such array elements, not their execution, because it is predefined in such example.</p>
  
  <p>But then how to generate an array of promises in such a way as to avoid early execution?</p>
  
  <p>Here's a modified example:</p>
  
  <pre><code>function sequence(nextPromise) {
      // while nextPromise() creates and returns another promise,
      // continue resolving it;
  }
  </code></pre>
  
  <p>I wouldn't want to make it into a separate question, because I believe it is part of the same problem.</p>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>Some answers below and discussions that followed went a bit astray, but the eventual solution that did exactly what I was looking for was implemented within <a href="https://github.com/vitaly-t/spex" rel="noreferrer">spex</a> library, as method <a href="http://vitaly-t.github.io/spex/global.html#sequence" rel="noreferrer">sequence</a>. The method can iterate through a sequence of dynamic length, and create promises as required by the business logic of your application.</p>
  
  <p>Later on I turned it into a shared library for everyone to use.</p>