JSFiddle - React, Tailwind, and code Playground

by David McClelland

HTML

<h1>
  Promises
</h1>

<hr />

<h2>
  Simple Promise
</h2>
<p>
  <label>Should promise succeed? : </label>
  <select id="promiseOptionSelect">
    <option value="yes" selected>Yes</option>
    <option value="no">No</option>
  </select>
  <input type="button" value="Start Promise" onclick="startPromise()" />
</p>
<p>
  <span id="promiseResult"></span>
</p>
<hr />
<h2>

JavaScript

function startPromise() {

  var p = new Promise(function(resolve, reject) {
    window.setTimeout(function() {
      var optionsSelect = document.getElementById("promiseOptionSelect");

      if (optionsSelect.options[optionsSelect.selectedIndex].value === "yes") {
        resolve("User chose to resolve this promise");
      } else {
        reject("User chose not to resolve this promise");
      }
    }, Math.random() * 2000 + 1000); //timeout of 1-2 seconds

  });

  // The canonical use for promises is calling out to some HTTP service to get data.
  // We cannot process the data until we get it, so we delay that processing inside the 
  // then() function.  If the data is unavailable for some reason, we will not be able
  // to proccess the data, so we implement the catch() to handle this result.
  p.then(function(data) { //then() is executed when resolve() is called inside the promise
    document.getElementById("promiseResult").innerHTML = "promise was fulfilled: " + data;
  }).catch(function(reason) { //catch() is executed when reject() is called inside the promise
    document.getElementById("promiseResult").innerHTML = "promise was rejected: " + reason;
  });

}

let updateValue = function(value) {
  return new Promise((resolve, reject) => {
    window.setTimeout(function() {
      document.getElementById("chainingResult").innerHTML += value.toString() + " | ";
      resolve(value + 1);
    }, 2000);
  });

};