Вы можете привязать cachedRequest
к себе как к контексту this
внутри функции.
cachedRequest = cachedRequest.bind(cachedRequest);
Обещания сохранят тот же контекст, что и функции стрелок, не создающие новый.
function cachedRequest(url) {
return new Promise((resolve, reject) => {
if (!this.responses) this.responses = {};
const cachedValue = this.responses[url]
console.log("function context => ", this.name);
console.log("this.responses => ", Object.keys(this.responses).length)
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)
})
})
}
cachedRequest = cachedRequest.bind(cachedRequest);
const URL = "https://pokeapi.co/api/v2/pokemon/ditto/"
cachedRequest(URL).then((response) => {
cachedRequest(URL)
console.log("window.responses =>", window.responses != undefined);
})