2017-02-16 41 views
2

我已经创建了一个数据服务,它从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?

回答

4

我想自从数据被缓存起来,而不是返回承诺它实际上是返回数据,并且原始数据上没有.then方法。

是的。

我怀疑我需要或者创建一个假的承诺(尽管它不是一个异步事务)返回数据时(使用Promise.resolve)缓存

可能的,但是没有。

...或改进我从我的数据服务(或返回数据)调用此方法的方式。

不,你当然不应该需要这个。

相反,有一个更简单的解决方案:缓存承诺对象本身,并从该网址的每次调用返回相同的承诺!

getData(url, use_cache = true) { 
    // Http Fetch Client to retreive data (GET) 
    if (use_cache && url in this.cache) 
    return this.cache[url]; 
    else 
    return this.cache[url] = this.httpClient.fetch(url, { 
     credentials: 'include' 
    }).then(response => response.json()); 
} 

这有你永远不会有对同一资源两个平行请求额外的好处 - 它本身被缓存的要求,不仅抵结果。唯一的缺点是你也缓存错误,如果你想避免这种情况并在随后的调用中重试,那么你必须放弃缓存。

+0

我只是说,这是一个惊人的解决方案!如果我能够对付它10次,我会! – LStarky