我获得了以下代码,用于异步检索数据并缓存数据以达到性能优化的目的:
let cache = {}
const optimizedFetch = async (url) => {
if (url in cache) {
// return cached result if available
console.log("cache hit")
return cache[url]
}
try {
const response = await fetch (url)
const json = response.json();
// cache response keyed to url
cache[url] = json
return json
}
catch (error) {
console.log(error)
}
}
optimizedFetch("https://jsonplaceholder.typicode.com/todos").then(console.log)上面的方法工作得很好,但是如果在等待第一个url的时候出现了对同一个url的第二个请求,那么就会触发第二个fetch。
你能告诉我如何改善这种情况吗?提前谢谢。
发布于 2020-09-08 18:44:42
let cache = {};
let awaits = {};
const optimizedFetch = (url) => {
return new Promise((resolve, reject) => {
if (url in cache) {
// return cached result if available
console.log("cache hit");
return resolve(cache[url]);
}
if (url in awaits) {
console.log("awaiting");
awaits[url].push({
resolve,
reject
});
return;
}
console.log("first fetch");
awaits[url] = [{
resolve,
reject
}];
fetch(url)
.then(response => response.json())
.then(result => awaits[url].forEach(({
resolve
}) => resolve(result)))
.catch(error => awaits[url].forEach(({
reject
}) => reject(error)))
.finally(() => {
delete awaits[url];
});
});
};
optimizedFetch("https://jsonplaceholder.typicode.com/todos")
.then(({
length
}) => console.log(length));
optimizedFetch("https://jsonplaceholder.typicode.com/todos")
.then(({
length
}) => console.log(length));
发布于 2020-09-08 18:24:03
只要把承诺作为一种价值。
工作实例:
let cache = {}
let totalRequests = 0;
const optimizedFetch = async(url) => {
if (cache[url]) return cache[url]; // return what we have
totalRequests++;
const fetchedRequest = fetch(url)
.then(response => response.json())
.then(json => {
cache[url] = json; // <-- we replace "Promise" result with json result
return json;
});
cache[url] = fetchedRequest; // <-- we keep Promise as a result
return fetchedRequest;
}
for (let i = 0; i < 5; i++) {
console.log('Setting request #', i);
optimizedFetch("https://jsonplaceholder.typicode.com/todos").then(result => console.log('Requests:', totalRequests, 'Result:', result.length));
}
解释:
totalRequests只是为了测试的目的,它向我们展示了如果缓存中有一个答案,我们生成了多少“真实”的来处理。
我的回答是被否决了,但我不明白为什么.它使用的是cache示例。请各位,如果你们投反对票,请评论上面,所以我会理解我的错误如果有的话。谢谢
https://stackoverflow.com/questions/63799045
复制相似问题