[英]IndexedDB - How to read max id in object store
我正在開發一個 web 應用程序,該應用程序從服務器讀取數據,為了節省成本,需要將數據存儲在瀏覽器上,以便它可以“增量”從服務器讀取數據,而不是每次都讀取它們,以減少網絡使用。
到目前為止,我所擁有的是:
function IXDBaddItems(osName, items, callback) {
const tx = db.transaction([osName], "readwrite");
const obj = tx.objectStore(osName);
items.forEach(item => {
obj.put(item);
})
tx.oncomplete = (event) => {
callback();
}
};
const getCorsiLastId = (lastId) => {
makeAjaxCall(urlCorsiVendite, "POST", {
ultimoId: lastId
})
.then(
(resp) => {
resp.forEach(d => {
d.id = +d.id;
d.id_course = +d.id_course;
d.id_user = +d.id_user;
d.insert_Date = new Date(d.insert_Date);
d.nome_corso = d.nome_corso;
d.year = +d.insert_Date.getFullYear();
d.month = +d.insert_Date.getMonth() + 1;
d.ref = +d.ref;
});
IXDBaddItems('corsiVendite', resp, () => console.log('db corsi update completed'));
},
(err) => console.log(err)
);
};
let db;
(async () => {
let request = window.indexedDB.open('dbKpiMarketing', 1);
// onerror handler signifies that the database didn't open successfully
request.onerror = (e) => {
console.log(e);
};
// onsuccess handler signifies that the database opened successfully
request.onsuccess = async(e) => {
console.log('Database opened successfully');
// Store the opened database object in the db variable. This is used a lot below
db = request.result;
getCorsiLastId(0);
};
// Setup the database tables if this has not already been done
request.onupgradeneeded = (e) => {
// Grab a reference to the opened database
let db = e.target.result;
// Create an objectStore to store our data
let osCorsi = db.createObjectStore('corsiVendite', {
keyPath: 'id'
});
let osServizi = db.createObjectStore('serviziVendite', {
keyPath: 'id'
});
console.log('Database setup complete');
};
})();
現在我用 lastId=0 調用 ajax function 來取回所有東西。 我需要使這個動態。 通過控制台中的這兩行代碼,我得到了我正在尋找的東西:最高存儲的 id。
let c = db.transaction('corsiVendite').objectStore('corsiVendite').getAll()
let lastIdCorsi = Math.max(...c.result.map(d=>d.id));
我需要在調用getCorsiLastId(LastIdCorsi)
之前獲取這兩行並運行它們但是如果我嘗試我得到一個錯誤: Uncaught (in promise) DOMException: Failed to read the 'result' property from 'IDBRequest': The request has not完成的。 我知道交易需要一些時間,所以我不能立即使用結果。 我該如何克服這個問題?
我想我解決了...實際上我已經使用事務的oncomplete方法在 IXDBaddItems function 中做了正確的事情。 我添加了這些行:
let t = db.transaction('corsiVendite', 'readwrite');
let o = t.objectStore('corsiVendite');
let c = o.getAll();
t.oncomplete = (e) => {
LastId = Math.max(...c.result.map(d=>d.id));
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.