我正在开发一个从服务器读取数据的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();
}
};
- 一个函数,在服务器上使用参数“lastId”进行增量 AJAX 调用,并最终将结果存储在objectStore中
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 函数来取回所有的东西。我需要使它动态化。通过控制台中的这两行代码,我得到了我想要的东西:存储的最高ID。
let c = db.transaction('corsiVendite').objectStore('corsiVendite').getAll()
let lastIdCorsi = Math.max(...c.result.map(d=>d.id));
我需要在调用getCorsiLastId(LastIdCorsi)
之前运行这两行代码,但是如果我尝试这样做,就会出现错误:* 未捕获(在承诺中)DOMException:无法从“IDBRequest”读取“result”属性:请求尚未完成。* 我知道交易需要一些时间,因此我无法立即使用结果。如何解决此问题?
1条答案
按热度按时间dojqjjoe1#
我想我解决了这个问题......实际上我已经在IXDBaddItems函数中使用事务的 oncomplete 方法做了正确的事情。我添加了以下行: