<!DOCTYPE html>
<html>

  <head>
    <title>Promises in chains</title>
    <script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
    <script data-require="moment.js@2.10.2" data-semver="2.10.2" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
    <button onclick="restart()">Restart</button>
    <ul id="status"></ul>
    <script src="script.js"></script>
    <script src="promises_chained.js"></script>
    <!--
    <script src="promises_unchained.js"></script>
     -->
   
  </body>

</html>
var $status;
var now = "";
var count;
var throwError;

$(function() {
  $status = $("#status");
  restart();
});

function restart() {
  $status.empty();
  count = 5;
  startPromiseChain();
}

function promiseChainDone() {
  if (--count > 0) {
    startPromiseChain();
  } else {
    show("Done");
  }
}

function getNumberAfterSomeTime() {
  return new Promise(function(resolve, reject) {
    var num = Math.random();
    if (throwError && num < 0.3) alerto();
    setTimeout(function() {
      if (num > 0.3) {
        resolve(num);
      } else {
        reject('Reject: ' + num.toFixed(2));
      }
    }, 1000);
  });
}

function show(str) {
  //now = (new moment()).format("HH:mm:ss");
  $status.append('<li>' + now + " " + str + '</li>');
  //console.log(str);
}
/* Styles go here */

button {
  cursor: pointer;
}
function startPromiseChain() {
  let num1, num2;
  
  throwError = false;
  
  getNumberAfterSomeTime()
  
  .then(function(val) {
    num1 = val;
    throwError = true;
  })
  
  .then(getNumberAfterSomeTime)
  
  .then(function(val) {
    num2 = val;
  })
  
  .then(getNumberAfterSomeTime)
  
  
  .then(function(val) {
    show("Result = " + (val * num1 * num2).toFixed(2));
    promiseChainDone();
  })
  
  .catch(function(exp) {
    show(exp);
    promiseChainDone();
  });
}
function startPromiseChain() {
  var num1, num2;
  throwError = false;

  getNumberAfterSomeTime()

  .then(function(val) {
    num1 = val;
    throwError = true;

    getNumberAfterSomeTime()

    .then(function(val) {
        num2 = val;
        
        getNumberAfterSomeTime()

        .then(function(val) {

          show("Result = " + (val * num1 * num2).toFixed(2));
          promiseChainDone();
        }, 
        
        function(exp) {
          show(exp);
          promiseChainDone();
        });
      },

      function(exp) {
        show(exp);
        promiseChainDone();
      });

  }, function(exp) {
    show(exp);
    promiseChainDone();
  });
}