title: Retrieving result of passed-in callback in JavaScript?
body: <p>I'm attempting to write a small wrapper around <code>localStorage</code> similar to how Rails fetches a cached result.  In Rails the pattern is like this:</p>
  
  <pre><code># Data.find is a block which just returns the data if the cache key was not found
  data = Rails.cache.fetch(key, options) { Data.find }
  </code></pre>
  
  <p>In JavaScript I'm having a difficult time getting the result of the callback which is executed to return the data if the cache is empty.</p>
  
  <pre><code>function fetch(key, callback) {
      var result = localStorage.getItem(key);
      if (result) {
          return JSON.parse(result);
      } else {
          result = callback();
          if (result) {
              result = JSON.stringify(result);
              localStorage.setItem(key, result);
          }
          return result;
      }
  }
  </code></pre>
  
  <p>I'm trying to use it like this:</p>
  
  <pre><code>var data = fetch('projects-delivered', function() {
      var result;
      d3.json('/projects/delivered.json', function(data) {
          result = formatDates(data);
      });
      return result;
  });
  </code></pre>
  
  <p>Data is always undefinded though.  Do I need to pass in another callback, or synchronize some how?  Or, is this not even possible with JavaScript's async nature?</p>