You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Promise异步从localStorage获取数据时报错如何解决?

localStorage数据读取报错问题记录

我在尝试从localStorage中获取数据时遇到报错,下方是我的实现代码,每一步都添加了注释标注预期执行逻辑,且已将原始JSON数据替换为示例数据集:

async function getData() {
    var dataAll = localStorage.getItem('requestAll')
    // 检查缓存中是否存在数据
    if( dataAll === null ) {
       // 缓存不存在则发起请求
       var responseAll = await fetch('https://data.cityofchicago.org/resource/xzkq-xp2w.json')
  
       // 解析json响应
       dataAll = await responseAll.json()
       
       // 将数据存入缓存
       localStorage.setItem('requestAll', JSON.stringify(dataAll));
    } else {
       // 缓存存在则直接解析
       dataAll = JSON.parse(dataAll)
    }
  
    // 返回数据
    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')
     // 从数据源拉取最新数据
    var responseAll = await fetch('https://data.cityofchicago.org/resource/xzkq-xp2w.json')
  
     // 解析json响应
     dataAll = await responseAll.json()
     
     // 将新数据存入缓存备用
     localStorage.setItem('request', JSON.stringify(dataAll));
     
     console.log('New data stored');
  
  // 返回新数据
  return dataAll
  }
  
  setTimeout(function(){
       grabNewData()
        console.log('Checking for new records');
  }, 10);

排查结果

已确认代码本身运行正常,报错原因是数据源体积过大,超出了localStorage的存储容量限制。

内容的提问来源于stack exchange,提问作者JS_basic_knowledge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:15:07