gpt4 book ai didi

javascript - 如何仅在indexeddb中添加一次初始数据

转载 作者:行者123 更新时间:2023-11-30 12:32:13 25 4
gpt4 key购买 nike

我正在创建一个 indexeddb,其中有几个商店。有一些必须在创建商店时最初添加的数据。

我有创建数据库和存储的功能:

function db_init(){
var request = indexedDB.open("db", "1.0");

request.onupgradeneeded = function(){
var db = request.result;
//store 1
db.createObjectStore("store1", {keypath: "id", autoIncrement: true});
//add initial datas;

//store2
db.createObjectStore("store2", {keypath: "id", autoIncrement: true});

//...
//store 3

// init necessary databases

db_populate();
}

request.onsuccess = function (){
db = request.result;
populate:db();
}
}

在 db_populate 函数中还有 4 个其他函数用于填充数据存储:

 function db_populate() {

init_store1();
init_store2();
//...

console.log("db populated with data");
}

每个 init_score 使用如下交易填充商店:

 var tx = db.transaction("store1", "readwrite");
var store = tx.objectStore("store1");

现在,我有一个问题。每次打开或刷新页面时,初始数据都会重复。有加过一遍。

当我在 onupgradeneeded 函数末尾添加 db_populate 时,出现错误:

  Uncaught TypeError: Cannot read property 'transaction' of undefined

在线:

  var tx = db.transaction ("store1", "readwrite");

我想要实现的是使用其初始数据创建一次数据存储,仅此而已。

知道我做错了什么吗?

提前致谢。

最佳答案

这是因为您无法在需要升级的事件中插入数据。您需要做的是在升级后关闭连接并再次重新打开它以插入数据。

流程应该是这样的:

function db_init() {
var request = indexedDB.open("db");
var dbShouldInit = false;
request.onupgradeneeded = function(e) {
var db = e.target.result;
dbShouldInit = true;
//store 1
db.createObjectStore("store1", {
keypath: "id",
autoIncrement: true
});
//add initial datas;

//store2
db.createObjectStore("store2", {
keypath: "id",
autoIncrement: true
});

}
request.onsuccess = function(e) {
e.target.result.close();
if(dbShouldInit)//executes only if DB init happened
db_populate(); //close the db first and then call init
}

}

function db_populate() {
init_store1(init_store2); //pass init 2 as callback
}

function init_store1(callback) {
var request = indexedDB.open("db");
request.onsuccess = function(e) {
var db = e.target.result;
var tx = db.transaction("store1", "readwrite");
var store = tx.objectStore("store1");

//init code here

tx.oncomplete = function(e) {
callback(); //here call the init for second function
};
}
}

function init_store2() {
var request = indexedDB.open("db");
request.onsuccess = function(e) {
var db = e.target.result;
var tx = db.transaction("store2", "readwrite");
var store = tx.objectStore("store2");

//init code here

tx.oncomplete = function(e) {
//here the app can continue
};
}
}

关于javascript - 如何仅在indexeddb中添加一次初始数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27359748/

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