gpt4 book ai didi

javascript - IndexedDB - 如何读取对象存储中的最大 ID

转载 作者:行者123 更新时间:2023-12-05 06:52:04 25 4
gpt4 key购买 nike

我正在开发一个从服务器读取数据的网络应用程序,为了节省成本,需要将数据存储在浏览器上,以便它可以“增量”从服务器读取数据而不是全部读取每次,以减少网络使用。

我目前拥有的是:

  • 将数组添加到现有对象存储的函数:
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) 之前获取这两行并运行它们,但如果我尝试这样做,我会收到错误消息:Uncaught (in promise) DOMException: Failed to read the “IDBRequest”的“结果”属性:请求尚未完成。我知道交易需要一些时间,所以我不能立即使用结果。我该如何克服这个问题?

最佳答案

我想我已经解决了...我实际上已经在 IXDBaddItems 函数中使用事务的 oncomplete 方法做了正确的事情。我添加了这些行:

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));
};

关于javascript - IndexedDB - 如何读取对象存储中的最大 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66030885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com