API调用后首次获取localStorage数据为null的解决方法
问题原因
这跟localStorage没关系,问题出在$.getJSON是异步请求,代码执行顺序乱了:
- 一开始
country_lang没定义,进入if分支发起API请求 - 浏览器不会等API返回结果,直接往下执行
localStorage.getItem('country_lang'),这时候数据还没存进localStorage,自然拿到null - 等API请求完成后,才会触发回调函数把数据存进去,这时候刷新页面(再次调用)才能读到值
解决方法
方案1:把依赖数据的逻辑塞进回调里
确保数据存好之后再去用它,把所有需要country_lang的代码都放在API成功回调里:
var country_lang = localStorage.getItem('country_lang'); if (!country_lang) { $.getJSON('https://api.ipregistry.co/?key=' + api_ipregistry_key, function(data) { country_lang = data.location.language.code; localStorage.setItem('country_lang', country_lang); alert(country_lang); // 首次调用就能拿到正确值 // 其他需要用到country_lang的逻辑都写在这里 }); } else { alert(country_lang); // 有缓存直接用 }
方案2:用async/await让代码更直观
把异步请求包装成Promise,用async/await让代码按顺序执行,看起来和同步代码一样:
async function getCountryLang() { let country_lang = localStorage.getItem('country_lang'); if (!country_lang) { // 把$.getJSON转换成Promise格式 const data = await new Promise((resolve) => { $.getJSON('https://api.ipregistry.co/?key=' + api_ipregistry_key, resolve); }); country_lang = data.location.language.code; localStorage.setItem('country_lang', country_lang); } alert(country_lang); return country_lang; } // 调用这个函数 getCountryLang();
内容的提问来源于stack exchange,提问作者Kelson Batista
相关产品推荐
相关产品推荐

