尝试使用IndexedDB。我编写了一个函数,该函数创建新的表和索引并返回回调。
但是当我尝试使用该功能时,它停止工作-在onsuccess
状态之后,我得到了onblocked
状态,而onupgradeneeded
无法运行...
如何避免阻塞数据库?
crtTable(db_name, table, indexes, callback) {
console.log("Initiate table creation");
let isSupport:boolean = this.checkDbSupport();
if(!isSupport) return;
let version;
let openRequest = indexedDB.open(db_name);
openRequest.onsuccess = (event) => {
console.log("Opening DB and find version");
version = (event.target as any).result.version;
//I GOT DB VERSION AND NOW I TRYING TO CLOSE IT!
(event.target as any).result.close();
version++;
console.log("reopen DB with new version")
let openRequest = indexedDB.open(db_name, version);
openRequest.onblocked = (event) => {
console.log("blocked");
}
openRequest.onupgradeneeded = (event) => {
console.log("update running")
let db = (event.target as any).result;
let transaction = db.createObjectStore(table[0], { keyPath: table[1] });
for(let index of indexes) {
transaction.createIndex(index[0], index[0], { unique: index[1] });
}
transaction.oncomplete = (event) => {
console.log("indexes setted");
}
callback("updated");
console.log("updated");
};
openRequest.onsuccess = (event) => {
openRequest.result.close();
callback("success");
console.log("success");
};
openRequest.onerror = (event) => {
openRequest.result.close();
callback("error");
console.log("error");
};
};
}
最佳答案
在将数据库升级到新版本之前,必须关闭其他数据库连接。
IDBOpenDBRequest.onblocked事件处理程序是阻止事件的事件处理程序。当由于版本更改而触发需要升级时触发该事件,但是即使在发送版本更改事件之后,数据库仍在某处使用(即未关闭)。
https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest/onblocked
更新:
您正在尝试在onsuccess
和onerror
事件上关闭它,并且由于数据库已经打开并且它调用onblocked
事件而未调用它,因此也尝试在onblocked
事件上关闭数据库。
openRequest.onblocked = (event) => {
(event.target as any).result.close();
console.log("blocked");
}
关于javascript - 取消阻止IndexedDB,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41549910/