2017-02-16 46 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