使用缓存或者对请求结果进行本地化存储
示例代码:
const cache = {};
fetch('http://example.com/data') .then(response => { if (cache['data']) { return cache['data']; } else { cache['data'] = response.json(); return cache['data']; } }) .then(data => { // 对数据进行处理 }) .catch(error => { console.log(error); });
const storageKey = 'exampleData';
if (localStorage.getItem(storageKey)) { // 若本地存储中已经有数据,则直接读取本地存储中的数据 const data = JSON.parse(localStorage.getItem(storageKey)); // 使用数据进行相关操作 } else { // 若本地存储中没有数据,则向服务器请求数据 fetch('http://example.com/data') .then(response => response.json()) .then(data => { localStorage.setItem(storageKey, JSON.stringify(data)); // 使用数据进行相关操作 }) .catch(error => { console.log(error); }); }