[英]Error when retrieving from localStorage async using promises
I am getting an error when trying to get data from localStorage.尝试从 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.
我还将 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);
EDIT: As per below, I have discovered that the code worked fine.编辑:如下所示,我发现代码运行良好。 The source was too big.
源头太大了。
Thank you.谢谢你。
I made a codesandbox of your code refactored.我重构了你的代码的代码沙盒。
The code looks like this:代码如下所示:
Note: The code won't run properly on Stackoverflow, since you are making a request and using localstorage.注意:代码将无法在 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); })();
Script worked fine.脚本运行良好。 The JSON data source was too big to store in cache.
JSON 数据源太大,无法存储在缓存中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.