我正在开发一个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();
}
};
- 一个函数,该函数在服务器上进行递增的ajax调用,并接受一个名为“lastId”的参数,最终将结果存储在对象存储中。
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)
);
};
- "async main body":异步主体
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函数来获取所有内容。我需要使其动态化。通过这两行代码,我可以获得我所需的内容:最高存储的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 finished.我理解事务需要一些时间,因此我不能立即使用结果。我该如何解决这个问题?