Using promise with async function

by Pasit R

HTML

<div class="container">
  <div class="row">
    <h1>Using promise with async function:</h1>
  </div>
  <br>
  <div class="row">
    <div class="append-range"></div>
  </div>
</div>

JavaScript

var args = {
  "7": "2016-01-07",
  "8": "2016-01-08",
  "9": "2016-01-09",
  "10": "2016-01-10",
  "11": "2016-01-11",
  "12": "2016-01-12",
  "13": "2016-01-13",
  "14": "2016-01-14",
  "15": "2016-01-15",
  "16": "2016-01-16",
  "17": "2016-01-17",
  "18": "2016-01-18",
  "19": "2016-01-19",
  "20": "2016-01-20",
  "21": "2016-01-21",
  "22": "2016-01-22",
  "23": "2016-01-23",
  "24": "2016-01-24",
  "25": "2016-01-25",
  "26": "2016-01-26",
  "27": "2016-01-27",
  "28": "2016-01-28",
  "29": "2016-01-29",
  "30": "2016-01-30",
  "31": "2016-01-31",
  "32": "2016-02-01",
  "33": "2016-02-02",
  "34": "2016-02-03",
  "35": "2016-02-04",
  "36": "2016-02-05"
};

$(function() {
  startProcess(args);

  function startProcess(arg) {
    var keys = Object.keys(arg);
    var index = 0;

    next();

    function next() {
      if (index >= keys.length) {
        console.log('done.');
        return;
      }

      var key = keys[index];
      var val = arg[key];
      console.log('next:', val);

      $.when(sendAsync(val)).then(onSuccess, onFail);

      index++
    }

    function sendAsync(val) {
      var defered = jQuery.Deferred();
      // Resolve after a random interval
      setTimeout(function() {
        defered.resolve("YES IT WORKED");
      }, Math.floor(400 + Math.random() * 2000));

      // Reject after a random interval
      setTimeout(function() {
        defered.reject("sorry");
      }, Math.floor(400 + Math.random() * 2000));

      return defered.promise();
    }

    function onSuccess(result) { // success
      console.log(result);
      $('.append-range').append(result);
      next();
    }

    function onFail(status) { // failed
      console.log(status + ", you fail this time");
      $('.append-range').append(status);
      next();
    }
  }

});