Promises for caching values

by Jason Green

HTML

<div id="out">

</div>

JavaScript

let cachedValue;

function someFunc(cb) {
	if (cachedValue) {
  	log('someFunc found cached value');
    cb(cachedValue);
  } else {
    log('someFunc fetched the value');
  	asyncronousThing(value => {
      cachedValue = value;
      cb(cachedValue);
    });
  }
}

function someOtherFunc(cb) {
	if (cachedValue) {
    log('someOtherFunc found cached value');
    	cb(cachedValue);
  } else {
  	log('someOtherFunc fetched the value');
  	asyncronousThing(value => {
      cachedValue = value;
      cb(cachedValue);
    });
  }
}

function asyncronousThing(cb) {
  setTimeout(() => cb(Math.random()), Math.random()*500);
}

log('Starting');
someFunc(value => log(value));
someOtherFunc(value => log(value));

setTimeout(() => {
	someOtherFunc(value => log(value));
}, 1000);





























function log(str) {
	var prev = document.getElementById('out').innerHTML;
  document.getElementById('out').innerHTML = prev + str + '<br>';
}