javascript - 如何实现在内部范围内缓存/记忆请求结果的功能
问题描述
我试图实现一个函数来发出缓存结果的请求。
要求是:
- 不能使用任何全局变量。
- 结果应该使用闭包存储在函数内部范围内。
如果不使用类,我找不到任何方法将结果存储在函数范围内。我尝试了以下代码,但我意识到this.responses
它实际上是一个全局变量window.responses
。有什么办法吗?
function cachedRequest(url) {
if (!this.responses) this.responses = {} // This is actually a global variable at window.responses, cant use it
return new Promise((resolve, reject) => {
const cachedValue = this.responses[url]
if (cachedValue) {
console.log('returning cached result')
return resolve(cachedValue)
};
fetch(url).then(res => {
console.log('fetching and caching result')
this.responses[url] = res
return resolve(res)
})
})
}
const URL = "https://pokeapi.co/api/v2/pokemon/ditto/"
cachedRequest(URL).then((response) => {
console.log({response})
cachedRequest(URL)
})
解决方案
您可以编写一个记忆函数,该函数在已使用的参数的闭包中进行跟踪。您可以在函数中注入每个回调memo
以保持存储打开。
它还使您能够注入任意数量的参数并使您的代码非常灵活。
const memo = (callback) => {
const cache = new Map();
return (...args) => {
const selector = JSON.stringify(args);
if (cache.has(selector)) return cache.get(selector);
const value = callback(...args);
cache.set(selector, value);
return value;
};
};
const cachedRequest = memo(fetch);
const URL = "https://pokeapi.co/api/v2/pokemon/ditto/";
cachedRequest(URL).then((response) => {
console.log(response);
cachedRequest(URL);
});
推荐阅读
- node.js - Vue 创建应用程序给出 /bin/sh: pnpm: command not found
- django - 查看所有控制台日志 Nginx gunicorn
- python-3.x - 如何从类中调用函数?错误是“X 对象没有属性 Y”
- javascript - 带有自定义声音的推送通知未在 iOS 中显示
- vb.net - 如何在 Visual Studio 中添加 MCSCM.dll 依赖项?
- mysql - 如何从 INNER JOIN 中按列排序
- python - 如何将列表转换为 str 以便我的 SQL 查询可以使用这些值?
- c - 试图遍历整个内存空间,过早重置地址变量
- bash - Cygwin bash脚本删除等号
- java - 使用自定义提交/回滚逻辑编写新事务管理器的建议