使用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
相关产品推荐
相关产品推荐

