Recibo un error al intentar obtener datos de localStorage.
Adjunté mi código a continuación e incluí comentarios sobre lo que creo que debería estar sucediendo con cada paso. También cambié los datos JSON a un conjunto de datos de muestra.
async function getData() { var dataAll = localStorage.getItem('requestAll') // check if data is in cache if( dataAll === null ) { // if it is not in cache then request it var responseAll = await fetch('https://data.cityofchicago.org/resource/xzkq-xp2w.json') // parse the json response dataAll = await responseAll.json() // store the data in the cache localStorage.setItem('requestAll', JSON.stringify(dataAll)); } else { // if it exists then parse it dataAll = JSON.parse(dataAll) } // return the data return dataAll } function waitForDomReady() { return new Promise(resolve => $(resolve)) } async function run() { try { var dataAll = await getData(); await waitForDomReady(); console.log(dataAll); var jsonString = localStorage.getItem("requestAll"); var dataAll = JSON.parse(jsonString); } catch (err) { console.log('error occured') } } run(); async function grabNewData() { var dataAll = localStorage.getItem('requestAll') // fetch new data from json source var responseAll = await fetch('https://data.cityofchicago.org/resource/xzkq-xp2w.json') // parse the json response dataAll = await responseAll.json() // store the new data in the cache ready for use localStorage.setItem('request', JSON.stringify(dataAll)); console.log('New data stored'); // return the new data return dataAll } setTimeout(function(){ grabNewData() console.log('Checking for new records'); }, 10);EDITAR: Según se indica a continuación, descubrí que el código funcionaba bien. La fuente era demasiado grande.
Gracias.
Hice un codesandbox de su código refactorizado.
El código se ve así:
Nota: el código no se ejecutará correctamente en Stackoverflow, ya que está realizando una solicitud y utilizando localstorage.
function getData() { console.log("running"); // check fir requestAll in local storage. null if it doesn't exist. const cache = localStorage.getItem("requestAll"); // if the data is in the cache, return it. if (cache) return Promise.resolve(JSON.parse(cache)); // else get the data and store it. return Promise.resolve( fetch("https://data.cityofchicago.org/resource/xzkq-xp2w.json") .then((res) => res.json()) .then((data) => { localStorage.setItem("requestAll", JSON.stringify(data)); return data; }) ); } (() => { getData().then(console.log); })();El guión funcionó bien. La fuente de datos JSON era demasiado grande para almacenarla en caché.