promises - baking a cake

by scotthannen

HTML

<div id="showOutput">Waiting for the cake...</div>

JavaScript

function mix(flour, eggs, sugar) {
  return flour + "," + eggs + "," + sugar + "_mixed";
}

function bake(batter) {
  return batter + "_baked";
}

function frost(cake, frosting) {
  return cake + "_frosted_with_" + frosting;
}

function deliverTheCake(cake) {
  document.getElementById("showOutput").textContent = "The cake is delivered: " + cake;
}

function makeExcuse(error) {
  document.getElementById("showOutput").textContent = "Sorry, can't finish the cake because: " + error;
}

///"Fake" fetch function
function fetch(ingredient) {
  return new Promise(function(resolve, reject) {
    window.setInterval(function() {
      if (Math.random() > 0.15) {
        resolve(ingredient);
      } else {
        reject("Unable to get the " + ingredient);
      }

    }, Math.random() * 5000);
  });
}

function getCake() {
  var getFrosting = fetch("frosting");
  var getBakingIngredients = Promise.all([fetch("flour"), fetch("eggs"), fetch("sugar")])
  var mixBakingIngredients = getBakingIngredients
    .then(function(ingredients) {
      return mix.apply(this, ingredients)
    });
  var bakeCake = mixBakingIngredients.then(bake);
  return Promise.all([bakeCake, getFrosting])
    .then(function(cakeAndFrosting) {
      return Promise.resolve(frost.apply(this, cakeAndFrosting));
    });
}

getCake().then(deliverTheCake).catch(makeExcuse);