我已经创建了一个数据服务,它从API获取数据集,但我想先让它在本地缓存并检查相同的数据是否已经可用(永远不要过时的数据因素......接下来我会处理这个问题)。这里是我的代码:在Aurelia中使用承诺进行数据检索和缓存
getData(url, use_cache = true) {
// Http Fetch Client to retreive data (GET)
let cache_index = this.cache.findIndex(r => { return r.url === url; });
if ((use_cache) && (cache_index > -1) && (this.cache[cache_index].data.length)) {
// Use cached data (available)
console.log("Found cached data!", this.cache[cache_index].data);
//
// I think this next line is the problem... need to return a promise???
//
return this.cache[cache_index].data;
} else {
console.log("Retrieving records from " + url);
return this.httpClient.fetch(url, {
credentials: 'include'
}).then(response => {
// Old statement was simple...
// return response.json();
// New method seems to be working because it's saving the data into the cache
return response.json().then(result => {
this.cache.push({'url': url, 'data': result});
// Not sure why I need this next line, but I do.
return result;
});
});
}
}
它工作正常检索数据的第一次,甚至在第二个电话,我可以看到(从控制台日志),它找到正确的缓存数据,但我发现我认为这个错误与承诺有关,这还不属于我的专业领域。
错误消息: ERROR [app-router] TypeError: this.core.getData(...).then is not a function
此错误实际上是在我的视图模型的调用者,它看起来像这样:
getAccounts() {
this.core.getData('/accounting/account/all').then(response => {
this.accounts = response;
});
}
我当数据被缓存,因为猜测而不是返回一个承诺,它实际上是返回数据,并且原始数据上没有.then
方法。
我怀疑我需要创建一个虚假承诺(即使它不是异步事务),以便在数据缓存时返回或改进从数据服务调用此方法的方式(或返回数据) 。
关于如何解决这个当前问题的任何想法?关于这个整个主题的任何免费建议,因为它涉及到Aurelia?
我只是说,这是一个惊人的解决方案!如果我能够对付它10次,我会! – LStarky