解锁 IndexedDB

3
尝试使用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");
        };
    };
}
1个回答

1

在升级数据库到新版本之前,您需要关闭其他数据库连接。

IDBOpenDBRequest.onblocked事件处理程序是blocked事件的事件处理程序。当出现版本更改但数据库仍然在某个地方(即未关闭)使用时(即使已发送versionchange事件),应触发此事件来触发upgradeneeded。

https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest/onblocked

更新:

你试图在onsuccessonerror事件上关闭它,但由于数据库已经打开并调用了onblocked事件,因此这些事件不会被调用。请尝试在onblocked事件上关闭数据库。

openRequest.onblocked = (event) => {
      (event.target as any).result.close();
      console.log("blocked");
 }

1
在获取当前的 DB 版本并在使用新版本打开新实例之前,我尝试使用(event.target as any).result.close();来关闭它...看起来好像不起作用。或者我做错了什么? - s.spirit
你正在尝试在 onsuccessonerror 事件上关闭它,但由于数据库已经打开并调用了 onblocked 事件,因此这些事件不会被调用。请尝试在 onblock 事件上关闭数据库。 - Nadir Laskar
哎呀...:/ 发现另一个已打开的实例,我忘记写 close() 了。我的错。 - s.spirit
关闭所有窗口并升级,它就能正常工作了 :) - Nadir Laskar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接