【发布时间】:2020-02-13 20:30:16
【问题描述】:
我正在尝试实现一个函数来发出缓存结果的请求。
要求是:
- 不能使用任何全局变量。
- 应使用闭包将结果存储在函数内部范围中。
如果不使用类,我无法找到将结果存储在函数范围内的任何方法。我尝试了以下代码,但我意识到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)
})
【问题讨论】:
标签: javascript caching promise scope closures