javascript fetch api 实现请求数据预负载均衡的核心做法是:在页面加载或用户交互前,使用 promise.allsettled() 并行发起多个 fetch 请求,并将结果缓存到内存中。当后续业务逻辑需要这些数据时,直接从缓存读取,从而避免串行等待和重复网络开销。

如何并行发起多个预加载请求并处理部分失败
通过 Promise.allSettled() 可以确保即使某个预加载请求失败(如网络超时或服务器错误),也不会阻塞其他请求的结果获取。这种方式比 Promise.all() 更健壮,适合对可用性要求较高的场景。

const urls = [
'https://api.example.com/data1',
'https://api.example.com/data2',
'https://api.example.com/data3'
];
async function preloadData() {
const promises = urls.map(url => fetch(url).then(res => res.json()));
const results = await Promise.allSettled(promises);
return results.map((result, index) => {
if (result.status === 'fulfilled') {
return { url: urls[index], data: result.value, status: 'success' };
} else {
return { url: urls[index], error: result.reason, status: 'failed' };
}
});
}
preloadData().then(console.log);运行上述代码将输出一个包含三个对象数组,每个对象标明对应 URL 的加载状态。若所有请求成功,则全部为 'success';若有失败,则对应项为 'failed' 并附带错误信息。
立即学习“Java免费学习笔记(深入)”;
如何将预加载结果存入全局缓存供后续使用
预加载完成后,应将结果存储在一个全局可访问的数据结构中,例如一个 Map 或普通对象。这样在后续组件渲染或事件触发时,可以直接从缓存中获取数据,无需再次发起网络请求。

const cache = new Map();
async function preloadAndCache(urls) {
const promises = urls.map(async url => {
try {
const response = await fetch(url);
const data = await response.json();
cache.set(url, { data, timestamp: Date.now() });
} catch (error) {
cache.set(url, { error, timestamp: Date.now() });
}
});
await Promise.all(promises);
}
// 示例调用
preloadAndCache(['https://api.example.com/user', 'https://api.example.com/settings']);
console.log(cache.get('https://api.example.com/user'));该程序会将每个 URL 对应的响应数据或错误信息存入 cache,并记录时间戳。后续可通过 cache.get(url) 快速获取已预加载的数据,提升用户体验。
基于预加载结果中的 timestamp 字段判断数据是否过期
在实际应用中,预加载的数据可能因长时间未更新而失效。可以通过检查缓存中每条记录的 timestamp 字段来判断其有效性。若当前时间与时间戳之差超过设定阈值(如 5 分钟),则视为过期,需重新发起请求。
function isStale(entry, maxAgeMs = 300000) {
return entry.timestamp + maxAgeMs < Date.now();
}
const userEntry = cache.get('https://api.example.com/user');
if (isStale(userEntry)) {
console.log('User data is stale, need refetch');
} else {
console.log('Using cached user data');
}此函数接收一个缓存条目和最大存活时间(毫秒),返回布尔值表示数据是否过期。结合前面的缓存机制,可实现智能刷新策略,平衡性能与数据新鲜度。


















