Dev*_*ish 9 html javascript indexeddb
我有以下要添加到 indexedDb 的对象数组:
const data = [
{ name: 'abc',
color: 'blue'
},
{ name: 'xyz',
color: 'red'
},
{ name: 'yui',
color: 'black'
}];
Run Code Online (Sandbox Code Playgroud)
现在我创建数据库并将这些数据插入到存储中,如下所示:
if (!db.objectStoreNames.contains("people")) {
peopleStore = db.createObjectStore("people", { keyPath: "name" });
peopleStore.createIndex("color", "color", { unique: false });
peopleStore.transaction.oncomplete = function(event) {
data.forEach(function(data) {
operations.add(data);
});
};
}
Run Code Online (Sandbox Code Playgroud)
add()我已经使用(在 a 内)方法定义了一个函数表达式,const operations如下所示:
add: function(data) {
let request = db
.transaction(["people"], "readwrite")
.objectStore("people")
.add(data);
}
Run Code Online (Sandbox Code Playgroud)
这是我的问题:
这种方式是在每次调用 add() 方法时创建一个新事务,还是将所有数据插入到单个事务中?
如果每次都创建一个新事务,我怎样才能只创建 1 个事务来提高性能并仅执行其中的所有操作。我猜我必须使用事务创建一个全局变量并对其执行操作(还有其他方法,例如edit(),delete()等,其中每个方法都有一个“ request”变量在其中定义事务,类似于我已经在上面展示了)。我应该创建一个像这样的全局变量:
const globalTrans = db.transaction(["people"], "readwrite").objectStore("people");
预先感谢所有花时间回复的人!:)
创建全局变量会产生问题。可能某个事务正在运行,而对于另一个操作,您可能会覆盖它。
例如-
var globalTx;
// let's say you are selecting data from people
globalTx = db.transaction(["people"], "read") // in read access
// and at same time you are inserting data from employee
globalTx = db.transaction(["employee"], "readwrite") // in read write
Run Code Online (Sandbox Code Playgroud)
解决问题的方法有很多种——
// for single value
function add(data) {
let request = db.transaction(["people"], "readwrite").objectStore("people").add(data);
}
// for multiple value
function addMultiple(datas, callback) {
const tx = db.transaction(["people"], "readwrite");
datas.forEach(data => {
let request = tx.objectStore("people").add(data);
})
tx.oncomplete = function(event) {
callback();
}
};
Run Code Online (Sandbox Code Playgroud)
// so now data will be only array
function add(datas, callback) {
const tx = db.transaction(["people"], "readwrite");
datas.forEach(data => {
let request = tx.objectStore("people").add(data);
})
tx.oncomplete = function(event) {
callback();
}
};
// so when want to insert single value , we will call like this.
const value = {
id: 1,
name: 'ujjwal'
}
add([value], () => {
})
Run Code Online (Sandbox Code Playgroud)
希望这能回答您的问题。