title: Break javascript promise chain in a clean way
body: <p>I am trying to chain promises so that the chain will break if one promise is rejected. I followed the leads of a <a href="https://stackoverflow.com/questions/20714460/break-promise-chain-and-call-a-function-based-on-the-step-in-the-chain-where-it">previous SO question</a> and tried to apply it to native promises, but I think I am misunderstanding the way things work.</p>
  
  <p>Here is how I have rewritten the code:</p>
  
  <pre><code>Promise.resolve()
      .then(function() {
          return step(1)
              .then(null, function() {
                  stepError(1);
              });
      })
      .then(function() {
          return step(2)
              .then(null, function() {
                  stepError(2);
              });
      })
      .then(function() {
          return step(3)
              .then(null, function() {
                  stepError(3);
              });
      });
  
  function step(n) {
      console.log('Step '+n);
      return (n === 2) ? Promise.reject(n) : Promise.resolve(n);
  }
  
  function stepError(n) {
      console.log('Error '+n);
      return Promise.reject(n);
  }
  </code></pre>
  
  <p>The output of the above code is:</p>
  
  <pre><code>Step 1
  Step 2
  Error 2
  Step 3
  [UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): 2]
  </code></pre>
  
  <p>In my understanding, step 2 should break the chain and step 3 should not be executed. When step(2) returns a rejected promise, stepError(2) is executed as expected. But since it returns Promise.reject(2), the function in the next then should not be executed, and since there is not catch in the end, the rejected promise of step 2 seems - as expected - to be forwarded until it exits the chain because it didn't find any handler.</p>
  
  <p>What am I missing here ?</p>
  
  <p>Here is a JSFiddle to play with: <a href="https://jsfiddle.net/6p4t9xyk/" rel="noreferrer">https://jsfiddle.net/6p4t9xyk/</a></p>