Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

269
Vistas
Error when retrieving from localStorage async using promises

I am getting an error when trying to get data from localStorage.

Have attached my code below, and included comments to what I think should be happening with each step. I have also swapped the JSON data to a sample data set.


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);
  

EDIT: As per below, I have discovered that the code worked fine. The source was too big.

Thank you.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I made a codesandbox of your code refactored.

Code on Codesandbox

The code looks like this:

Note: The code won't run properly on Stackoverflow, since you are making a request and using 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);
})();

about 4 years ago · Juan Pablo Isaza Denunciar

0

Script worked fine. The JSON data source was too big to store in cache.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda