簡體   English   中英

使用承諾從 localStorage async 檢索時出錯

[英]Error when retrieving from localStorage async using promises

嘗試從 localStorage 獲取數據時出現錯誤。

在下面附上了我的代碼,並包含了對我認為每一步應該發生的事情的評論。 我還將 JSON 數據交換為示例數據集。


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

編輯:如下所示,我發現代碼運行良好。 源頭太大了。

謝謝你。

我重構了你的代碼的代碼沙盒。

代碼沙盒上的代碼

代碼如下所示:

注意:代碼將無法在 Stackoverflow 上正常運行,因為您正在發出請求並使用 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); })();

腳本運行良好。 JSON 數據源太大,無法存儲在緩存中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM