Request.JSON

sending a JSON request to the jsFiddle backend. Later on parse and display the data.

by Greg Milby

JavaScript

var getCache = function(key) {
  var storageDfd = new jQuery.Deferred(),
      storedData = localStorage.getItem(key);

  if (storedData) {
    setTimeout(function() {
      storageDfd.resolveWith(null, [JSON.parse(storedData)]);
    });
    return storageDfd.promise();
  }

  // data is for jsfiddle demo only
    var data = { json: { foo: 'bar' } };
  return jQuery.getJSON(key, data).then(function(data) {
    localStorage.setItem(key, JSON.stringify(data));
  }).promise();
};

// usage

function go() {
  console.log(1);

  getCache('/echo/json/').then(function(data) {
    console.log(2);
    console.log(data);
  });

  console.log(3);
}

// call getCache the first time, uses json request
go();

// call it a second time later, pulls from local storage, and fires in async order
setTimeout(go, 3000);